JSR 303 Bean Validation + Javascript Client-Side Validation

jsr 303 hibernate validator
jsr 380
jsr-303 vs spring validation
jsr 303 custom validator
jsr 303 baeldung
jsr-349
does not conform to the jsr 303 specifications.
jsr 303 maven

What is the best way to perform client-side form validation using Javascript (with minimal code duplication) when using JSR 303 bean validation on the server side? I'm currently using Spring 3 and the Hibernate Validator.

I would suggest that you look at Spring JS, which relies heavily on Dojo. A tutorial can be found here.

Easiest way for yourself to start playing with it is to download Spring Roo, create the petclinic sample application with one of the example-scripts (this takes you 5 minutes) and then play around with how the javascript is integrated. Spring Roo creates an app with the same technology stack that you use (Spring+hibernate+implementation of jsr 303)

Bean Validation Made Simple With JSR 303, JSR 303: Bean Validation This JSR will define a meta-data model and API for JavaBeanTM validation based on annotations, with overrides and extended  JSR-303 bean validation is a specification whose objective is to standardize the validation of Java beans through annotations. The objective of the JSR-303 standard is to use annotations directly in a Java bean class. This allows validation rules to be specified directly in the code they are intended to validate, instead of creating validation rules in separate classes.

I found this open source project but it looks dead, maybe it is worth resurrecting.

http://kenai.com/projects/jsr303js/pages/Home

This library provides client side validation of an HTML form based on JSR-303 and Hibernate Validator annotations, integrated with Spring MVC. The library provides a JavaScript validation code base that handles basic interaction with HTML forms, as well as JavaScript functions implementing the validation annotations supported by Hibernate Validator (including those not from the JSR-303 spec). This JavaScript code base can be included in a page by using a provided taglib or by extracting the JavaScript file from the jar and including it using a tag. Once this code base has been included in a page, a second taglib is used to generate the JavaScript code for validating an HTML form. You can also provide a JSON object in the body of the tag to specify additional configuration information.

detail JSR# 303, JSR-303 bean validation is a specification whose objective is to standardize the validation of spring mvc beans through annotations. The objective of the  JSR-303 bean validation has become the validation standard in the Java world. Bean validation API provides an object level constraint declaration and validation facility for the Java application developer, and a constraint metadata repository and query API.

Here's how I'm doing it using Spring MVC + JQuery + Bootstrap, partially based on a recent blog post at SpringSource:

AddressController.java

@RequestMapping(value="/validate")
public @ResponseBody ValidationResponse processForm(Model model, @Valid AddressForm addressForm, BindingResult result) {
    ValidationResponse res = new ValidationResponse();
    if (result.hasErrors()) {
        res.setStatus("FAIL");
        for (ObjectError error : result.getAllErrors()) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                res.addError(fieldError.getField(), fieldError.getDefaultMessage());
            }    
        }
    }
    else {
        res.setStatus("SUCCESS");
    }
    return res;
}

AddressForm.java

public class AddressForm {
    @NotNull
    @Size(min=1, max=50, message="Address 1 is required and cannot be longer than {max} characters")
    private String address1;

    @Size(max=50, message="Address 2 cannot be longer than {max} characters")
    private String address2;

    // etc
}

ValidationResponse.java:

public class ValidationResponse {
    private String status;
    private Map<String,String> errors;
    // getters, setters
}

address.jsp:

<f:form commandName="addressForm">
    <div class="control-group">
        <label for="address1">Address 1</label>
        <div class="controls">
            <f:input path="address1" type="text" placeholder="Placeholder Address 1" class="wpa-valid" />
            <span class="help-inline"></span>
        </div>
    </div>
    <!-- etc -->
    <div class="form-actions">
        <button type="submit" class="btn btn-primary">Save</button>
        <button type="button" class="btn">Cancel</button>
    </div>
</f:form>

<script type="text/javascript">
function collectFormData($fields) {
    var data = {};
    for (var i = 0; i < $fields.length; i++) {
        var item = $($fields[i]);
        data[item.attr("id")] = item.val();
    }

    return data;
}

function clearErrors($fields) {
    for (var i = 0; i < $fields.length; i++) {
        var item = $($fields[i]);
        $("#"+item.attr("id")).parents(".control-group").removeClass("error");
        $("#"+item.attr("id")).siblings(".help-inline").html("");
    }
}

function markErrors(errors) {
    $.each(errors, function(key, val) {
        $("#"+key).parents(".control-group").addClass("error");
        $("#"+key).siblings(".help-inline").html(val);
    });
}

$(document).ready(function() {
    var $form = $("form.validate");
    $form.bind("submit", function(e) {
        var $fields = $form.find(".validate");

        clearErrors($fields);
        var data = collectFormData($fields);

        var validationUrl = "validate";
        $.get(validationUrl, data, function(response) {
            $("#alert").removeClass();

            if (response.status == "FAIL") {
                markErrors(response.errors);

                $("#alert").addClass("alert alert-error");
                $("#alert").html("Correct the errors below and resubmit.");
            } else {
                $("#alert").addClass("alert alert-success");
                $("#alert").html("Success!");

                $form.unbind("submit");
                $form.submit();
            }
        }, "json");

        e.preventDefault();
        return false;
    });
});
</script>

It could use some refactoring, but this will do an ajax GET with the form data and update the page based on the result.

Spring Bean Validation Example with JSR-303 Annotations, Java Bean Validation (JSR 303) originated as a framework that was approved by the JCP as of 16 November 2009 and accepted as part of the Java EE 6  The legacy Before getting the result that is JSR 303, aka the Bean Validation framework, there were two interesting attempts at validation framework. Each came from an end of the layers and focused

Richfaces supports this. They have a small demo on their site.

Bean Validation, First, the JSR-303 Bean Validation API is now fully supported. Second, when used programatically, Spring's DataBinder can now validate objects as well as bind  Before getting the result that is JSR 303, aka the Bean Validation framework, there were two interesting attempts at validation framework. Each came from an end of the layers and focused on its scope.

PrimeFaces Client Side Validation Framework Supports Bean Validation.

http://blog.primefaces.org/?p=2874

5.7 Spring 3 Validation, JSR 380 is a specification of the Java API for bean validation, part of Jakarta EE and JavaSE, which ensures that the properties of a bean meet  JSR 303: Bean Validation. Bean Validation Expert Group /** * Determine if the Bean Validation provider is allowed to cascade validation on * the bean instance

Java Bean Validation Basics, JSR 303 - Bean Validation - defines a metadata model and API for entity validation. The default metadata source is annotations, with the ability to override and  This library provides client side validation of an HTML form based on JSR-303 and Hibernate Validator annotations, integrated with Spring MVC.

Java Validation API (JSR-303) - Developer, JSR 303 - Bean Validation - defines a metadata model and API for entity validation. The default metadata source is annotations, with the ability to override and  JSR 303 - Bean Validation - defines a metadata model and API for entity validation. The default metadata source is annotations, with the ability to override and extend the meta-data through the use of XML. The API is not tied to a specific application tier or programming model.

[PDF] Hibernate Validator JSR 303 Reference Implementation Reference , Maven Dependencies. To use Spring bean validation in our project, we need to add validation-api and JSR-303 implementation in our pom.xml  15 Answers15. Active Oldest Votes. 280. Each field constraint should be handled by a distinct validator annotation, or in other words it's not suggested practice to have one field's validation annotation checking against other fields; cross-field validation should be done at the class level.

Comments
  • Definitely going to test this. Setting the validation on the bean and having it automatically replicated on the client is the way to go