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 currentl
Edit:
Indeed JSR 303 is the best way (IMO) to handle client side validation. The best thing is that if you have proper js libraries on the fronted you can use the same validation (the same code) on the server (if you would use node.js). I've created library @stopsopa/validation for this purposes I'm validating forms like this (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 (
);
}
}
ReactDOM.render( , document.getElementById("root"));
live example is available here: https://codesandbox.io/s/ymwky9603j