0

I have a numeric input field that is allowed to be empty, but if is not empty I'd like to return a validation error if letters are entered for example.

at the moment if I removed allow empty validation works just fine for both numeric and notEmpty but this field is optional how can I fix this?

Here is the validation on my model:

'tickets' => array(
    'numeric' => array(
        'rule' => 'numeric',
        'message' => 'Please enter only numbers',
        'allowEmpty' => true,
    ),
),

once again if I set allowEmpty to false this works as expected. I've been playing around with it by separating the rules, but so far no luck. Any help is appreciated.

ndm
  • 59,784
  • 9
  • 71
  • 110

1 Answers1

1

You specify "allowed to be empty" and "optional" in a way that leads me to think that what you're after is actually required, which you should set to false.

required => true does not mean the same as the validation rule notEmpty(). required => true indicates that the array key must be present - it does not mean it must have a value. Therefore validation will fail if the field is not present in the dataset, but may (depending on the rule) succeed if the value submitted is empty (‘’).

So

'tickets' => array(
    'numeric' => array(
        'rule' => 'numeric',
        'message' => 'Please enter only numbers',
        'allowEmpty' => true,
        'required' => false,
    )
),

would mean that it is ok for the field to be "optional" (not included in the returned array), if it is included it is "allowed to be empty" and if it isn't the rule is "numeric".

user221931
  • 1,852
  • 1
  • 13
  • 16
  • Thank you very much for your reply. However I did find the root of the problem. The problem was that cakephp adds the "input type" automatically on the input field with the form helper. Since it is a field "type INT" in the database it gets added a "type"=>"number" so the browser never sends any data for cake to validate if letters are typed in. Now, If I override the HTML input to "type"=>"text" (which is not accurate since it's a number) data is now sent to cakephp and validation kicks in. Maybe you've seen this issue before, any other suggestions? – user3804467 Jul 06 '14 at 21:03
  • That's not a problem, it's a rather new feature of browsers in HTML5. You should never trust that the browser or the user will send proper data, always validate your input. For the problem description my answer is appropriate. If your problem is how to bypass the browser's field validation please do your research and if needed open a new question. – user221931 Jul 07 '14 at 00:28