Skip to main content

Adding an onvalidate Event Handler

When the form save method executes, Zen invokes the onvalidate event-handler method, if one is defined, for each of the form controls. By implementing an event-handler for a form control we can provide validation for the corresponding field of the form.

Add validation to the State field by completing the following steps:

  1. Add the following client-side method to HomePage.cls

    
     ClientMethod validateState(comp) [ Language = javascript ]
    {
       //State value must be exactly two capital letters
       return (/^[A-Z]{2}$/.test(comp.getValue()));
    }        
    
    
  2. Add values for the onvalidate and invalidMessage attributes of the “State” <text> element. Update the element to look like this

    
    <text label="State" dataBinding="State" size="2"
        onvalidate="return zenPage.validateState(zenThis);" 
        invalidMessage="State must contain 2 capital letters" 
        required="true"
    />            
     
    

Note the following about this validation code:

  • If validateState returns false the form is invalid.

  • validateState returns false if the State field of the form contains anything other than two capital letters. Note that the method is not invoked if the field is empty. In order to validate that the field is not empty, we set required=true on the component.

  • A reference to the text component is passed to validateState using the zenThis variable.

Note:

To learn more about Zen form validation, read Validating Forms in the Zen Forms section of Using Zen Components.

FeedbackOpens in a new tab