JSR 303 Bean Validation + Javascript Client-Side Validation

后端 未结 7 1131
感情败类
感情败类 2021-01-30 20:48

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

7条回答
  •  一整个雨季
    2021-01-30 21:08

    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 (
          
    {s.validate && s.errors.name && (
    {s.errors.name}
    )}
    {s.validate && s.errors.email && (
    {s.errors.email}
    )}
    ); } } ReactDOM.render(, document.getElementById("root"));

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

提交回复
热议问题