Skip to content

Commit

Permalink
Added ability to customise validation errors (#113)
Browse files Browse the repository at this point in the history
* Added ability to customise validation errors

* Added documentation for validation
Made validationErrorMessages a method that can be overridden

* Update Readme.md

* Update Field.php
  • Loading branch information
chrispage1 authored and Mikk Mihkel Nurges committed Jul 20, 2018
1 parent 6ac2feb commit 52c207a
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
22 changes: 22 additions & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,28 @@ When you execute a mutation, it will return any validation errors that occur. Si
}
```


The validation errors returned can be customised by overriding the `validationErrorMessages` method on the mutation. This method should return an array of custom validation messages in the same way documented by Laravel's validation. For example, to check an `email` argument doesn't conflict with any existing data, you could perform the following -

Note: the keys should be in `field_name`.`validator_type` format so you can return specific errors per validation type.


````php

public function validationErrorMessages ($args = [])
{
return [
'name.required' => 'Please enter your full name',
'name.string' => 'Your name must be a valid string',
'email.required' => 'Please enter your email address',
'email.email' => 'Please enter a valid email address',
'email.exists' => 'Sorry, this email address is already in use',
];
}

````


#### File uploads

For uploading new files just use `UploadType`. This support of uploading files is base on https://github.com/jaydenseric/graphql-multipart-request-spec
Expand Down
17 changes: 16 additions & 1 deletion src/Rebing/GraphQL/Support/Field.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@ public function args()
return [];
}

/**
* Define custom Laravel Validator messages as per Laravel 'custom error messages'
* @param array $args submitted arguments
* @return array
*/
public function validationErrorMessages(array $args = [])
{
return [];
}


protected function rules(array $args = [])
{
return [];
Expand Down Expand Up @@ -155,7 +166,11 @@ protected function getResolver()
$rules = call_user_func_array([$this, 'getRules'], [$args]);
if(sizeof($rules))
{
$validator = Validator::make($args, $rules);

// allow our error messages to be customised
$messages = $this->validationErrorMessages($args);

$validator = Validator::make($args, $rules, $messages);
if($validator->fails())
{
throw with(new ValidationError('validation'))->setValidator($validator);
Expand Down

0 comments on commit 52c207a

Please sign in to comment.