Validating data php

Rated 4.55/5 based on 961 customer reviews

Where, ‘field Name’ is the name of the field the rule is defined for, and ‘rule Name’ is a pre-defined rule name, such as ‘alpha Numeric’, ‘email’ or ‘is Unique’.

For example, to ensure that the user is giving a well formatted email address, you could use this rule: true, the form validation will not function correctly. As you can see here, each field (only one field shown above) is associated with an array that contains five keys: ‘rule’, ‘required’, ‘allow Empty’, ‘on’ and ‘message’. The ‘rule’ key defines the validation method and takes either a single value or an array.

For the login field, only letters and numbers will be accepted, the email should be valid, and born should be a valid date.

Defining validation rules enables Cake PHP’s automagic showing of error messages in forms if the data submitted does not follow the defined rules.

If ‘required’ is evaluated to true, the field must be present in the data array.

For example, if the validation rule has been defined as follows: must be present - it does not mean it must have a value.

The specified ‘rule’ may be the name of a method in your model, a method of the core Validation class, or a regular expression.

The ‘on’ key can be set to either one of the following values: ‘update’ or ‘create’.

The email should be a valid email address, and born should be a valid date.

Also, notice how you can define specific error messages that Cake PHP will use when these validation rules fail.

Now that you’ve seen the big picture on how validation works, let’s look at how these rules are defined in the model.

There are three different ways that you can define validation rules: simple arrays, single rule per field, and multiple rules per field.

Leave a Reply