Search code examples
validationcakephpserver-side

Cakephp Validation tweak


I have added multiple validation rule for one field

Array
(
    [email] => Array
    (
        [rule] => email
        [message] => Please input a valid email address
    )
    [notEmpty] => Array
    (
        [rule] => notEmpty
        [message] => This field is required
    )

)

I want if filed empty then error should be "This field is required" and if its invalid mail address then "Please input a valid email address".

I am getting email address error in both case.

Thanks in advance


Solution

  • You need to switch the order of the validation rules so that it checks notEmpty first. What is happening is that if the field is blank it is invalidating the field as not being a valid email (because it is not) and not hitting the second rule.

    You could also try adding 'allowEmpty' => true to the email rule as this would skip the validation rule if the field is empty, but it is best to make sure you order the rules according to the order you want/need them evaluating in (it makes the code more readable).

    Array
    (
        [notEmpty] => Array
        (
            [rule] => notEmpty
            [message] => This field is required
        )
        [email] => Array
        (
            [rule] => email
            [message] => Please input a valid email address
            [allowEmpty] => true
        )
    
    )