Validators: Into the Deep - Constants and Variables
(Page 3 of 4 )
Constants
Reusability is the core of the Validator framework. So it is unthinkable that there wouldn’t be a way to reuse the rules. The approach provided by the framework is in the form of constants. A constant is a rule defined in the <global > tag that can be used to replace a Field's property attribute, the Field's <var> element value attribute, the Field's <msg> element key attribute, and the Field's arg0-arg3 element's key attributes. So whatever rules are set using the <constant> tag, they can be used to replace the same rule if it recurs. To make things clear, let's see an example:
<global>
<constant>
<constant-name>zip</constant-name>
<constant-value>^\d{5}(-\d{4})?$</constant-value>
</constant>
</global>
The constants are declared within the <constant> </constant> tag. The constants have to be given using the <constant-name> tag. Here the name is zip, as this constant is being used to check the zip value being entered. Next <constant-value> is used to specify the actual rule. Here the rule is a regular expression.
<field
property="zip"
depends="required,mask">
<arg0 key="registrationForm.zippostal.displayname"/>
<var>
<var-name>mask</var-name>
<var-value>${zip}</var-value>
</var>
</field>
Then the constant can be used by its name as seen in the <var> node’s <var-value> element’s value. The evaluation of the constant is done using EL.
Variables
When variables must be passed to be used by a pluggable Validator, variables are used. Variables are specified by the <var> tag. An example would clarify it further:
<field property="name" depends="required,maxlength">
<arg0 key="customer.name"/>
<arg1 name="maxlength" key="${var:maxlength}" resource="false"/>
<var>
<var-name>maxlength</var-name>
<var-value>30</var-value>
</var>
</field>
The variable is declared and defined using the <var> tag. The first child node of <var> defines the name of the variable. Here the name of the variable is maxlength. Then the value to be used is specified using the <var-value> tag. Here the value is 30. The variable can be used as a value of the key attribute of field element.
In a nutshell, constants can be used to represent the rules that can become part of the <var-value>, whereas the variable can be used to provide the value of key attributes of <arg1> at runtime.
Next: Registration Form: Putting it All Together >>
More JavaScript Articles
More By A.P.Rajshekhar