Data Validation
Data validations can be performed in either a controller or a model class. In either case, Scooter Framework provides a set of built-in validators. You may also add in your own validators.
Built-in Validators
Scooter Framework has the following built-in validators.
Method | Description |
---|---|
validatesPresenceOf | validates the fields have non-blank values. |
validatesConfirmationOf | validates the fields match their corresponding confirmation values. A field's confirmation field name is "${field_name}_confirmation". |
validatesAcceptanceOf | validates the fields match the accepted values. This method is usually used for validating acceptance of service agreement checkbox. The default accepted value is "1". |
validatesInclusionOf | validates each field matches one of the specified values. |
validatesExclusionOf | validates each field excludes from the specified values. |
validatesNotNull | validates the field data is not null. |
validatesIsEmail | validates the field data contains email only. |
validatesIsNumber | validates the field data contains number only. |
validatesNumberMaximum | validates the field data does not exceed maximum. |
validatesNumberIsLowerThanOrEqualTo | validates the field data is lower than or equal to a specific number. |
validatesNumberIsLowerThan | validates the field data is lower than a specific number. |
validatesNumberIsLargerThanOrEqualTo | validates the field data is larger than or equal to a specific number. |
validatesNumberIsLargerThan | validates the field data is larger than a specific number. |
validatesNumberIsEqualTo | validates the field data is equal to a specific number. |
validatesNumberIsWithinRangeOf | validates the field data is within a specific range of [number1, number2]. |
validatesNumberIsInsideRangeOf | validates the field data is in a specific range of (number1, number2). |
validatesLengthMaximum | validates the maximum length of a field. |
validatesLengthMinimum | validates the minimum length of a field. |
validatesLengthInRangeOf | validates the field length is in a specific range. |
validatesLengthOf | validates the field length is as specified. |
validatesUniqenessOf | validates each field data is unique. |
Writing a Validation Method
Validation in Controller
ActionControl gives us two helper methods for data validation: validators() and validationFailed() method.
The following is an example of using validation methods. If the user failed to submit username or password in a login request, the validateInput before filter can stop the request and redirect the request to the login page. The authenticate method will not be invoked.
public class SignonController extends ApplicationController { public void registerFilters() { //apply validateInput filter only to the authenticate() method beforeFilter("validateInput", "only", "authenticate"); } public String validateInput() { validators().validatesPresenceOf("username"); validators().validatesPresenceOf("password"); if (validationFailed()) { flash("error", "Please submit both username and password."); return ActionResult.redirectTo("/signon/login"); } return null; } ... }
Validation in Model
Validation has been built in ActiveRecord implementation. Validation is triggered before a record is created, updated, or saved. You may put in your validation code by overriding the following methods:
- public void validatesRecordBeforeCreate()
- public void validatesRecordBeforeUpdate()
- public void validatesRecordBeforeSave()
- public void validatesRecordBeforeDelete()
- public void validatesRecord()
The default implementation of the first three methods all delegate validations to the validatesRecord() method. Therefore if you only override the validatesRecord() method, your validation will take into effect when a record instance is created, or updated or saved. If you want validate a delete request, you need to override the validatesRecordBeforeDelete method. The default implementation of the validatesRecordBeforeDelete method does nothing.
The following is an example of overriding the validatesRecord() method.
public class Tweet extends ActiveRecord { public void validatesRecord() { validators().validatesLengthMaximum("message", 140); } ... }
If the validation fails, the built-in validation message associated with property key validation.too_long in message resource files will be used as the validation error. The validation message is like the following:
message is too long (maximum is 140 characters).
Scooter Framework is very flexible. If you don't like the built-in message for "validation.too_long", you may change the message in a message resource file or you can do it in your code as follows:
public class Tweet extends ActiveRecord { public void validatesRecord() { validators().validatesLengthMaximum("message", 140, "Please limit your tweet within 140 characters."); } ... }
Here, a custom validation message will be displayed as the following:
Please limit your tweet within 140 characters.
Differences of Validation methods in Controller and in Model
As you can see from the above examples, validation methods in controller and model classes are difference.
A validation method in a controller class is very similar to an action method of a controller. It has the following characters:
- It takes no input parameters.
- It returns a string to either redirect to a new action or forward to a view.
- It returns null if there is no validation error.
- You may use filter to link it with other action methods.
A validation method in a model class is slightly different:
- It takes no input parameters.
- It has no return value.
- You must override a validation method in ActiveRecord class.
Retrieving Validation Results
ValidationResults class is the holder for all validation messages.
ValidationResults class is used in Controller and Model classes.
Retrieving Validation Results in Controller
Validation results are stored in the controller instance.
They can be retrieved by using the ActionControl instance's currentValidationResults() method.
Retrieving Validation Results in Model
Validation results are stored in the record instance.
They can be retrieved by using the active record instance's getValidationResults() method. The method returns a ValidationResults instance.
Creating Your Own Validator
You may create your own validators. The way to do it is slightly different in a Controller and in a Model class.
Creating Your Own Validator in Controller
You create your own validators in a controller as follows:
1. Extend the ActionValidators class.
2. Override the validators() method by returning an instance of the subclass of the ActionValidators class.
3. Write a filter method by using the returned instance.
Creating Your Own Validator in Model
You create your own validators in a model as follows:
1. Extend the ModelValidators class.
2. Override the validators() method by returning an instance of the subclass of the ModelValidators class.
3. Write a validation method by using the returned instance.