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
stopsopa Dec 05 '18 at 0:15 2018-12-05 00:15
source share