Model reference
Reference Figure: Anatomy of a Validation Script
A validation script has three parts: the input it receives, the rules it applies and the messages it returns. This figure shows how the parts fit together.
A validation script is a small, focused piece of logic. It receives a value, applies a set of rules and returns a result. It does not write to the database and it does not render a page. That narrow scope makes it easy to test and easy to reuse.
The three parts
- Input. The value under test, usually a form object or a single field.
- Rules. Required, length, format, range and cross field checks.
- Result. A list of messages, each tied to a field and a message key.
Writing a rule
Start with the field name and the failure condition. Keep each rule independent so that one failure does not hide another. When a rule needs data from more than one field, express it as a separate method with a descriptive name. The generated test starter calls each rule with a valid and an invalid value.
customer.email.invalid can be translated without touching the script.Avoid database calls inside a validation script. If a rule needs to know whether a value already exists, call a service method that performs one targeted query, and treat the result as an input to the rule.