Monday, December 3, 2012

Zend Framework 2 (ZF2) - Validate a Check Box

If you have a registration form with a terms and conditions check box you'll probably want to validate that it is checked. This can be accomplished by using the Digits Validator.

Start by defining your input as follows: ...

Notice that the checked_value = 1.
Notice also that the unchecked_value = 'no'.
Look at the Zend\Validator\Digits class and notice that it validates the following:
...

The check box will fail validation when it is 'unchecked' because it contains the alpha characters ('no'). So next we create our input filter for our terms check box and give the 'NOT_DIGITS' our custom message.
...

I am still a little bummed out that decorators are no longer used but am impressed with some of the new capability provided by ZF2.


Master Control Program:  You're in trouble, program. Why don't you make it easy on yourself. Who's your user? 

Tron 1982

4 comments:

  1. I was trying for days with injecting custom message to the NotEmpty validator for checkbox until I found your idea... Thanks!!

    ReplyDelete
  2. Why didn't you use just input filter:

    'required' => false

    ?

    ReplyDelete
    Replies
    1. oh, I meant 'required' => true.

      Delete
  3. Great post. Thank you for sharing such a great information about Zend Framework

    ReplyDelete