Skip to content
Chandra Sekar S edited this page Aug 24, 2010 · 1 revision

Grasshopper provides models with support for validations. Models can use the built-in validators or perform their own custom validations. Models which perform validations must implement a validate() function, which will be invoked whenever the model is validated. The current validity of models can be determined using the isValid() function on the model.

Validation errors can be accessed in views using <%= error(modelObj, propName[, locale]) %>.

#Built-in Validators

The following validator methods are available to all models out of the box.

###validateRequired(propName[, error[, prefix]])

Error Key: required

Validates whether the given property has a value in the model.

###validateNumeric(propName[, error[, prefix]])

Error Key: numeric

Validates whether the value of the given property is a number.

###validateDate(propName[, error[, prefix]])

Error Key: date

Validates whether the value of the given property is a valid date.

###validatePattern(propName, pattern, [, error[, prefix]])

Error Key: pattern

Validates whether the value of the given property matched the given RegExp.

#Custom Validations

Models can perform validations other than the built-in ones and add their own custom errors to the model using addError().

###addError(propName, error[, prefix])

Adds the error to the specified property.

#Internationalization

By default all validations assumed that the error messages are internationalized. Hence, they prefix the error key specified with ModelConstructorName.propName. The error keys used by built-in validators are specified above. This behaviour can be customized by specifying the prefix and error arguments. If prefix is false, the error keys are not prefixed. If we assume a model named 'Person' these are the possible usages and their effects.

validateRequired('name') - Custom, internationalized error message for the specific model type. validateRequired('name', false) - Same internationalized error message for similar validations across all models. validateRequired('name', 'Name is required.', false) - No internationlization. The locale argument must be omitted in this case in views.

Clone this wiki locally