SoFunction
Updated on 2025-04-07

Instance code for form validation using async validator in React

Form verification in react is undoubtedly cumbersome, especially for forms that are dynamically added or deleted, the verification logic is more complicated. Currently, the UI framework uses material ui, but its form processing is not ideal. I then studied another UI framework ant design, which greatly facilitates the writing of logic. It uses async-validator to process verification logic.

Currently, it is undoubtedly unrealistic to replace the framework, so I wanted to directly introduce async-validator. The following describes a simple use. For specific information, you can check it on github.

import Schema from 'async-validator';
/*
 * @params form: {
 * descriptor: Verification rules
 * source: field to be verified
 * callback: Asynchronous verification callback function
 * }
 *
 * @return errInfo {
 * isAllValid: Verify whether it passes
  * errors: field information that failed to verify
 * }
 * Regardless of whether the verification result is successful or failed, the result information will be written into errors, so that the caller can directly obtain verification result information through array subscripting.
 * */
function validate (form) {
  let errInfo = {};
  let errStatus = [];
  let descriptor = ;
  let validator = new Schema(descriptor);
  (, {
    firstFields: true // If a field corresponds to multiple verification rules, only the first rule information that failed verification will not be validated.  }, (errors, fields) => {
    if (errors) {
      /* If you need asynchronous verification, you need to pass in the callback function callback */
      (item => {
        ();
      });
       = errors;
       = !(true);
       && (errInfo);
    }
  });
  return errInfo;
}export default validate;


/**
 * Created by wxw on 18-4-26.
 */
import React from 'react';
import {inject} from 'mobx-react';
import { withStyles } from 'material-ui/styles';
import validate from '../utils/validate';
import {formTest2} from '../utils/validateRules';
import Input, { InputLabel } from 'material-ui/Input';
import { FormControl, FormHelperText } from 'material-ui/Form';
import { MenuItem } from 'material-ui/Menu';
import Select from 'material-ui/Select';
import Button from 'material-ui/Button';
const styles = theme => ({
  container: {
    display: 'flex',
    flexWrap: 'wrap',
  },
  formControl: {
    margin: ,
  },
  button: {
    margin: ,
    color: '#fff'
  },
});
@inject('rootStore')
@withStyles(styles)
class FormTest2 extends  {
  state = {
    name: {
      value: '',
      errStatus: false,
      errMsg: 'Please entername'
    },
    age: {
      value: '',
      errStatus: false,
      errMsg: 'Please selectage'
    }
  };
  handleChange =(field) => event => {
    if (field === 'name') {
      ({ name: (, {value: }) });
    } else if (field === 'age') {
      ({ age: (, {value: }) });
    }
  };
  handleCheck = (field) => () => {
    if (field === 'name') {
      let errInfo = validate({
        descriptor: formTest2,
        source: {
          name: ,
        }
      });
      ({ name: [0].message});
    } else if (field === 'age') {
      let errInfo = validate({
        descriptor: formTest2,
        source: {
          age: ,
        }
      });
      ({ age: [1].message });
    }
  };
  handleSubmit = () => {
    let {name, age} = ;
    let errInfo = validate({
      descriptor: formTest2,
      source: {
        name: ,
        age: 
      }
    });
    (item => {
      ({
        []: 
      });
    });
    if () {
      ('Verification is successful');
    } else {
      ('Verification failed');
    }
  };
  render () {
    const { classes } = ;
    const {name, age} = ;
    return (
      <div className="form2">
        <FormControl className={} error={}>
          <InputLabel htmlFor="name-simple">Name</InputLabel>
          <Input  value={} onChange={('name')} placeholder="placeholder" onBlur={('name')} />
          <FormHelperText >{}</FormHelperText>
        </FormControl>
        <FormControl className={} error={}>
          <InputLabel htmlFor="age-simple">Age</InputLabel>
          <Select
            value={}
            onChange={('age')}
            onBlur={('age')}
            inputProps={{
              name: 'age',
              id: 'age-simple',
            }}
          >
            <MenuItem value={10}>Ten</MenuItem>
            <MenuItem value={20}>Twenty</MenuItem>
            <MenuItem value={30}>Thirty</MenuItem>
          </Select>
          <FormHelperText >{}</FormHelperText>
        </FormControl>
        <Button variant="raised" color="primary" className={} onClick={}>
          submit
        </Button>
      </div>
    )
  }
}

export default FormTest2;


/**
 * Created by wxw on 18-4-26.
 */
export const formTest2 = {
  name: {
    validator(rule, value, callback, source, options) {
      /* callback must be executed once, with parameters as error message, without parameters as correct */
      if (value) {
        callback({
          errMsg: "Please enter name",
          value,
          errStatus: false
        });
      } else {
        callback({
          errMsg: "name cannot be empty",
          value,
          errStatus: true
        });
      }
    }
  },
  age: {
    validator(rule, value, callback, source, options) {
      /* callback must be executed once, with parameters as error message, without parameters as correct */
      if (value) {
        callback({
          errMsg: "Please select age",
          value,
          errStatus: false
        });
      } else {
        callback({
          errMsg: "Required Options",
          value,
          errStatus: true
        });
      }
    }
  },
};

To sum up, it is a small demo, which can be packaged in a deeper level for use.

Summarize

The above is the example code for using async validator in React to perform form verification that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!