JSR 303 Bean Validation + Javascript Client Validation

What is the best way for client-side validation using Javascript (with minimal code duplication) when using server-side JSR 303 bean validation? I am currently using Spring 3 as a Hibernate Validator .

+43
java javascript spring validation bean-validation
Mar 25 '10 at 8:05
source share
7 answers

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

The easiest way to start playing with it is to download Spring Roo , create an application for the example with piclinks with one of the examples - scripts (it will take you 5 minutes), and then play with how javascript integrates. Spring Roo creates an application with the same technology stack that you are using (Spring + hibernate + jsr 303 implementation)

+5
Mar 25
source share

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

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

This library provides client-side validation of HTML forms 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 formats, as well as JavaScript functions that implement validation annotations supported by the Hibernate Validator (including not from the JSR-303 specification). This JavaScript code base can be included in the page using the provided taglib or by extracting the JavaScript file from the jar and including it using the tag. After this code base has been included in the page, the second taglib is used to generate JavaScript code to validate the HTML form. You can also provide a JSON object in the tag tag to provide additional configuration information.

+5
Jun 14 2018-12-12T00:
source share

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

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 may use some refactoring, but it will do ajax GET with form data and refresh the page based on the result.

+4
Sep 13 '12 at 3:14
source share

Richfaces supports this. They have a small demonstration on their website .

+1
Jun 23 2018-12-12T00:
source share

PrimeFaces Client Side Validation Framework supports Bean Validation.

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

0
Aug 28 '13 at 12:12
source share

Here is an open source alternative for JSR-303.

This solution can do all the verification of the request message, but error coding is not required.

https://github.com/ckpoint/CheckPoint

With a checkpoint, all verification is possible without further code, simply by changing the annotation of the controller method.

After that, all verification parameters can be easily done on the admin page.

I think this video will help you understand. https://youtu.be/I1aEIztXlhE

Check-Point Setup Screen

0
Jul 30 '18 at 12:21
source share

Edit:

Indeed, JSR 303 is the best way (IMO) to validate client-side validation. Best of all, if you have your own js libraries at the front, you can use the same check (same code) on the server (if you use node.js). I created the @ stopopa / validation library for these purposes. I check for such forms (In React.js):

 import React, { Component } from "react"; import ReactDOM from "react-dom"; import validator, { Collection, Required, Optional, NotBlank, Length, Email, } from "@stopsopa/validator"; class App extends Component { constructor(...args) { super(...args); this.state = { data: { name: "", email: "" }, errors: {}, validate: false }; } onSubmit = async e => { e.preventDefault(); const errors = await validator(this.state.data, new Collection({ name: new Required([ new NotBlank(), new Length({min: 3}), ]), email: new Required([ new NotBlank(), new Email(), ]) })); this.setState({ errors: errors.getFlat(), validate: true, }); if ( ! errors.count()) { console.log('send data to server', this.state.data); } }; onChange = (name, value) => { this.setState(state => ({ ...state, data: { ...state.data, ...{ [name]: value } } })); }; render() { const s = this.state; return ( <form onSubmit={this.onSubmit}> <label> name: <input value={s.data.name} onChange={e => this.onChange("name", e.target.value)} /> </label> {s.validate && s.errors.name && ( <div className="error">{s.errors.name}</div> )} <br /> <label> email: <input value={s.data.email} onChange={e => this.onChange("email", e.target.value)} /> </label> {s.validate && s.errors.email && ( <div className="error">{s.errors.email}</div> )} <br /> <input type="submit" value="submit" /> </form> ); } } ReactDOM.render(<App />, document.getElementById("root")); 

A live example is available here: https://codesandbox.io/s/ymwky9603j

0
Dec 05 '18 at 0:15
source share



All Articles