Respect Validation and custom messages


#1

hi

Im using Respect validation and would like to add a custom error message to it.
I dont what to display the “fname not alphanumeric” in the message it must display “First name not alphanumeric”

//UserController
class UserController extends BaseController {

  public function postSignUp(SEmail $semail, View $view) {

         $validation = $this->validator->validate($this->request, [
            'fname' => v::notBlank()->alpha(' '),
            'lname' => v::notBlank()->alpha(' '),
         ]);


         if ($validation->failed()) {
             return $this->redirect('auth.signup');
         }

        // do more stuff
 }
//Validator.php
namespace Ti\Support\Validation;

use Ti\Support\Validation\Contracts\ValidatorInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Respect\Validation\Exceptions\NestedValidationException;

class Validator implements ValidatorInterface {

    protected $errors = [];

    public function validate(Request $request, array $rules) {

        foreach ($rules as $field => $rule) {
            try {
                $rule->setName(ucfirst($field))->assert($request->getParam($field));
            } catch (NestedValidationException $e) {
                $this->errors[$field] = $e->getMessages();
            }
        }

        $_SESSION['errors'] = $this->errors;
        return $this;
    }

    public function failed() {
        return !empty($this->errors);
    }
}


#2

You should open an issue to Respect library.
Slim does not have this dependency.

Please read their documentation:
http://respect.github.io/Validation/docs/

Or open an issue:


#3

Thanks Damianopetrungaro.

I found the answer it relates to the setName variable.

can you help with the php syntax.I need to check if the setname have a value. I tried the isset


 foreach ($rules as $field => $rule) {
            try {

              if ( isset($rule->setName))
               {
                    // If setName found for rule, use setName value
                    $rule->assert($request->getParam($field)); 
     
                }else {
                      // setName not found, create setName using field variable 
                     $rule->setName(ucfirst($field))->assert($request->getParam($field));
                }




} catch (NestedValidationException $e) {
                $this->errors[$field] = $e->getMessages();
            }
        }





#4

Hi, if you use the setName() function on all fields you want to validate, then in your validator.php you can just use:

	foreach ($rules as $field => $rule) {
		try {
			$rule->assert($request->getParam($field));
		} catch (NestedValidationException $e) {
			$this->errors[$field] = $e->getMessages();
		}
	}