Reputation: 12873
I have been using Respect Validation for form Validation
$app->post('/', function () use ($app) {
$validator = v::key('name', v::string()->notEmpty())
->key('email', v::email()->notEmpty())
->key('message', v::string()->notEmpty());
$errors = array();
try{
$validator->assert($_POST);
} catch (\InvalidArgumentException $e) {
$errors = $e->findMessages(array(
'notEmpty' => '{{name}} is required',
'email' => '{{name}} must be a valid email'
));
}
if ($validator->validate($_POST)) {
// do stuff
$app->redirect('/');
} else {
$app->render('index.php', array('field_errors' => array_values($errors)));
}
});
looping through array_values($errors)
would give me:
"" is required
email must be a valid email
I need something like:
name is required
email must be a valid email
message is required
How should it be done using Respect Validation
Upvotes: 3
Views: 4845
Reputation: 755
I think the answer two above this is close. You just need to add an error message code block that includes the message as well as the name and email.
$errors = $e->findMessages(array(
'notEmpty' => '{{name}} is required',
'email' => '{{email}} must be a valid email',
'notEmpty' => '{{message}} please enter a message'
));
Upvotes: 0
Reputation: 8721
The messages are there but your findMessages
lookup is searching for notEmpty
and email
.
What you actually have in $errors
are :
Array
(
[0] =>
[1] => email must be a valid email
)
$errors[0]
is your lookup for notEmpty
which wasn't found.
$errors[1]
is your lookup for email
which was found.
If you change it to look for the fields in question name
, email
and message
:
$errors = $e->findMessages(array(
'name' => '{{name}} is required',
'email' => '{{name}} must be a valid email',
'message' => '{{name}} is required'
));
Then you will get the desired results :
Array
(
[0] => name is required
[1] => email must be a valid email
[2] => message is required
)
Excuse the delayed response I purely stumbled on this by chance, you will find much quicker results if requesting support from the official Respect\Validation issue tracker instead. This would also be the ideal platform for any suggestions you may have for improvements to help avoid the problems you've experienced. You will find the Respect team eager, friendly and always willing to help.
nJoy!
Upvotes: 4