[NFR] Validator's correct behavior
1- No validator should be triggered for empty fields except 'required' validator. 2- By default validation should stop on first failure.
Currently non of above is implemented correctly.
Disagree, but
If field is empty and 'required' validator is absent then other validators should be skipped. This is a very common scenario: the field must either be empty or have a valid format.
+1 Agent-J
use Phalcon\Validation\Validator\PresenceOf,
Phalcon\Validation\Validator\Email;
$validation = new Phalcon\Validation();
//$validation->add('email', new PresenceOf(array(
// 'message' => 'The e-mail is required'
//)));
$validation->add('email', new Email(array(
'message' => 'The e-mail is not valid'
)));
Because if email is optional field (there is not PresenceOf for email field) and field is empty validation still fails.
You can tell the validator to stop the validation if the first validator fails: http://docs.phalconphp.com/en/latest/reference/validation.html#validation-cancelling
But still I can not use an empty string in the email field.
The "canBeEmpty" option in the validators would be helpful.
I don't think that the Email validator should allow empty strings because its task is validate emails and an empy string is not a valid email, you can create a variant this way:
<?php
class EmailEmptyValidator extends Phalcon\Validation\Validator\Email
{
/**
* Executes the validation
*
* @param Phalcon\Validation $validator
* @param string $attribute
* @return boolean
*/
public function validate($validator, $attribute)
{
$value = $validator->getValue($attribute);
if ($value === null or $value === '') {
return true;
}
return parent::validate($validator, $attribute);
}
}
Then stop the validation if
$validation->add('email', new EmailEmpty(array(
'message' => 'The e-mail is not valid'
)));
What about if the email or any other field is optional but the correct format is required? Thank you for the example. For me is enough.
As mentioned before (several times), we can't break the current behavior also this is not a bug is the intended behavior.
You're the boss... but it's very inconvenient behavior that makes a lot of problems. Why the validator should check the field format if this field is empty and optional?
I was referring about the original "bug" in this issue, regarding the validation if empty, can you please open a NFR for that?
oh! thanks =) Here we are https://github.com/phalcon/cphalcon/issues/690
thanks!