Validating WebFlow Models

From Skyway Wiki

Jump to: navigation, search

There are many instances when you need to validate a form in Skyway's Spring WebFlow editor, and you require validation to occur on the server side. One approach to accomplish this use case is creating a Spring validator class to validate a model from a view state. This article will describe the steps to enable Spring's Validator class on a Skyway WebFlow using the PAM example.

First, take a gander at the Spring Docs on the subject about Validating Models. Most notably, focus on the Implementing a Validator section.

Second, take a look at our PAM tutorial, or just download the finished version.

Third, follow these steps to add validation to the Appraisal Edit screen:

  1. Create a Validator class in the form ${model}Validator, where ${model} is the capitialized form of the model expression. In PAM, add a class in src/com.pam.web named AppraisalValidator.java. Note, in PAM both the Domain Object and WebFlow variable are named appraisal. Use whatever name you give the WebFlow variable for your class name. For example, in FirstSkywayBank a LoanAccount domain object exits, but a variable named loanApplication is defined in the WebFlow. This would result in a LoanApplicationValidator.java validator class.
  2. Add a private method to validate the view state in the form validate${View state}. In AppraisalValidator.java, add a private method called validateEdit to validate the view state. The full AppraisalValidator.java is shown below
    package com.pam.web;
    
    import org.springframework.binding.message.MessageBuilder;
    import org.springframework.binding.message.MessageContext;
    import org.springframework.binding.validation.ValidationContext;
    import org.springframework.stereotype.Component;
    import com.pam.domain.Appraisal;
    @Component
    public class AppraisalValidator {
    public void validateEdit(Appraisal appraisal, ValidationContext context)
    {
    MessageContext messages = context.getMessageContext();
    if (appraisal.getEmployeeNo().length() < 4 ) {
    messages.addMessage(new MessageBuilder().error().source("employeeNo").defaultText("Invalid Employee Number.").build());
    }
    }
    }
    This code validates employee numbers are greater than 4 characters.
  3. Add a error field in the WebContent/WEB-INF/flows/appraisalentry/edit.jsp under the employeeNo input field as shown below:
    <form:errors path="employeeNo" cssClass="error" element="div" />
    Don't forget to add the spring forms tag library to the page: <%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

That's it! Enjoy validating!

Personal tools