Sunday 5 January 2014

Client Side Validation example of PrimeFaces

Introduction

With the latest version of PrimeFaces, version 4, you have the possibility to perform some validations on the client, by the browser.
This features doesn’t replace the standard JSF validation on the server side but is an addition to it.  The server side validation makes sure that any data posted to the server is valid before it is processed any further. The client side validation is there to inform user faster of data problems.
By default, all the standard validations like required fields, minimum and maximum values, string lengths and so on are available.  But you can also create the JavaScript version of your custom JSF validation.
The feature is very good explained in the PrimeFaces users guide. This posts describes the steps that I have done to make a Visa card validation on the client side.

Configuration

In order to activate the feature, you need to put the following content parameter in the web.xml file.
    <context-param>
        <param-name>primefaces.CLIENT_SIDE_VALIDATION</param-name>
        <param-value>true</param-value>
    </context-param>

Now, your application is ready to use the client side validation feature. And whenever you want to make use of it, you just have to specify the attribute validateClient on the commandButton tag for example.

The standard validations known by PrimeFaces are then performed on the fields in the form.  Any validation error is shown by the messages or growl tag which is also available in the form.

Make sure you read the PrimeFaces users guide to know all the requirements and usages.  The most import ones are


  • Put a messages or growl tag within the form. others are not yet discovered. 
  • Severity attribute of these tags is ignored.
  • Invalid fields are marked by a red border but associated label isn’t colored

These shortcomings will be removed in the next release of the framework.

Custom validation

It is also possible to have a client side validation variant of your custom validations.  Therefor I created an example, a visa card number validation.

You start by creating a standard JSF validator, so a class that implements Validator interface.  For the Client Side Validation feature of PrimeFaces, you have to implement also the org.primefaces.validate.ClientValidator interface.

It contains 2 methods, getValidatorId which defines the name of the JavaScript function that implements the validation on the client side. If the JavaScript function needs some values defined by the validator (like the minimum value for the range validation) you have to return it by the getMetadata method.

This is the java side of the solution
@FacesValidator("custom.VisaCardCheck")
public class VisaCardValidator implements Validator, ClientValidator {
    @Override
    public Map<String, Object> getMetadata() {
       return null;  // No metadata required on client side
    }

    @Override
    public String getValidatorId() {
        return "custom.VisaCardCheck";
    }

    @Override
    public void validate(FacesContext someFacesContext, UIComponent someUIComponent, Object o) throws
            ValidatorException {
        ...
    }
}


The JavaScript must be available on the page where we like to use it, the code is shown below.
PrimeFaces.validator['custom.VisaCardCheck'] = {
    reverse: function (s) {
        var o = '';
        for (var i = s.length - 1; i >= 0; i--)
            o += s[i];
        return o;
    },
    throwError: function(detail) {
        throw {
            summary: 'Validation Error',
            detail: detail
        }
    },
    validate: function (element, value) {
        var reg = /^\d+$/,
            digits = this.reverse(value).substring(1).split(""),
            sum = 0;
        if (!value.match(reg)) {
            this.throwError("Not all digits");
        }
        if (value.length < 13 || value.length > 16) {
            this.throwError("Length invalid");
        }
        if (value.charAt(0) != '4') {
            this.throwError("Wrong start digit");
        }
        for (var i = 0; i < digits.length; i++) {
            if (i%2 == 0) {
                digits[i] = digits[i] * 2;
                if (digits[i] > 9) {
                    digits[i] = digits[i] - 9
                }
            }
            sum += parseInt(digits[i]);
        }
        if (value.charAt(value.length - 1) != (sum % 10)) {
            this.throwError("Check digit validation fails");
        }
    }
};


The important thing here is that the name of the validator in the JavaScript object, custom.VisaCardCheck in my case, is the same as the value returned by the getValidatorId method of the JSF validator.

Usage of the validator at the JSF level is the same as usual.
<p:inputText id="myValue" value="#{dataBean.myValue}" required="true" validator="custom.VisaCardCheck" />

Conclusion


With the Client Side Validation framework, we can inform the user faster about issues with data, without the need to go to the server.

The best thing is that it integrates very well with JSF and it is hard to tell if the message came from the client side validation or from the server side.

The default validations are already available in their javaScript counterpart, also if you use BeanValidation. When you create a custom validation, you have to write the JavaScript yourself, of course.

No comments:

Post a Comment