Validation 表单校验

表单校验。

何时使用#

同表单结合使用,对表单域进行校验,提供前台校验和后台实时反馈校验,并对表单错误提供有效信息提示。

API#

<Validation>
  <Validator>
    <CustomComponent>
      <input />
    </CustomComponent>
  </Validator>
</Validation>

Validation#

属性 类型 说明
onValidate func 当内部 Validator 开始校验时被调用。
方法 说明
validate(callback) 对所有表单域进行校验。
reset() 将表单域的值恢复为初始值。
forceValidate(fields, callback) 对指定的表单域进行校验,fields 对应每个 Validator 包裹的表单域的 name 属性值。

Validation.Validator#

一个 Validator 对应一个表单域,校验的表单域需要声明 name 属性作为校验标识,如 <input name="username" />

属性 类型 默认值 说明
rules array 或者 object 支持多规则校验,默认提供的规则详见 async-validator,同时支持用户自定义校验规则。
trigger String onChange 设定如何触发校验动作。

rules 说明(async-validator#

示例: {type: "string", required: true, min: 5, message: "请至少填写 5 个字符。" }

  • type : 声明校验的值类型(如 string email),这样就会使用默认提供的规则进行校验,更多详见 type
  • required: 是否必填;
  • pattern: 声明校验正则表达式;
  • min / max: 最小值、最大值声明(对于 string 和 array 来说,针对的是其长度 length。);
  • len: 字符长度;
  • enum: 枚举值,对应 type 值为 enum,例如 role: {type: "enum", enum: ['A', 'B', 'C']}
  • whitespace: 是否允许空格, true 为允许;
  • fields: 当你需要对类型为 object 或者 array 的每个值做校验时使用,详见 fields
  • transform: 当你需要在校验前对值做一些处理的时候;
  • message: 自定义提示信息,更多
  • validator: 自定义校验规则。

代码演示

import {Validation, Button, Form, Input} from 'antd';
const Validator = Validation.Validator;
const FormItem = Form.Item;

function cx(classNames) {
  if (typeof classNames === 'object') {
    return Object.keys(classNames).filter(function(className) {
      return classNames[className];
    }).join(' ');
  } else {
    return Array.prototype.join.call(arguments, ' ');
  }
}

function noop() {
  return false;
}

const Demo = React.createClass({
  mixins: [Validation.FieldMixin],

  getInitialState() {
    return {
      status: {
        email: {},
        name: {},
        passwd: {},
        rePasswd: {},
        textarea: {}
      },
      formData: {
        email: undefined,
        name: undefined,
        passwd: undefined,
        rePasswd: undefined,
        textarea: undefined
      },
      isEmailOver: false, // email 是否输入完毕
      emailValidateMethod: 'onBlur' // 用于改变 email 的验证方法
    };
  },

  renderValidateStyle(item) {
    const formData = this.state.formData;
    const status = this.state.status;

    const classes = cx({
      'error': status[item].errors,
      'validating': status[item].isValidating,
      'success': formData[item] && !status[item].errors && !status[item].isValidating
    });

    return classes;
  },

  handleEmailInputBlur() {
    this.setState({
      isEmailOver: true
    });
  },

  handleEmailInputFocus() {
    if (this.state.isEmailOver) {
      this.setState({
        emailValidateMethod: 'onChange'
      });
    }
  },

  handleReset(e) {
    this.refs.validation.reset();
    this.setState(this.getInitialState());
    e.preventDefault();
  },

  handleSubmit(e) {
    e.preventDefault();
    this.setState({
      isEmailOver: true
    });
    const validation = this.refs.validation;
    validation.validate((valid) => {
      if (!valid) {
        console.log('error in form');
        return;
      } else {
        console.log('submit');
      }
      console.log(this.state.formData);
    });
  },

  userExists(rule, value, callback) {
    if (!value) {
      callback();
    } else {
      setTimeout(function () {
        if (value === 'JasonWood') {
          callback([new Error('抱歉,该用户名已被占用。')]);
        } else {
          callback();
        }
      }, 800);
    }
  },

  checkPass(rule, value, callback) {
    if (this.state.formData.passwd) {
      this.refs.validation.forceValidate(['rePasswd']);
    }

    callback();
  },

  checkPass2(rule, value, callback) {
    if (value && value !== this.state.formData.passwd) {
      callback('两次输入密码不一致!');
    } else {
      callback();
    }
  },

  render() {
    const formData = this.state.formData;
    const status = this.state.status;

    return (
      <Form horizontal>
        <Validation ref="validation" onValidate={this.handleValidate}>
          <FormItem
            label="用户名:"
            id="name"
            labelCol={{span: 7}}
            wrapperCol={{span: 12}}
            validateStatus={this.renderValidateStyle('name')}
            hasFeedback
            help={status.name.isValidating ? '正在校验中..' : (status.name.errors && status.name.errors.join(','))}
            required>
              <Validator rules={[{required: true, min: 5, message: '用户名至少为 5 个字符'}, {validator: this.userExists}]}>
                <Input name="name" id="name" value={formData.name} placeholder="实时校验,输入 JasonWood 看看" onChange={this.setField.bind(this, 'name')} />
              </Validator>
          </FormItem>

          <FormItem
            label="邮箱:"
            id="email"
            labelCol={{span: 7}}
            wrapperCol={{span: 12}}
            validateStatus={this.renderValidateStyle('email')}
            hasFeedback={this.state.isEmailOver}
            help={status.email.errors ? status.email.errors.join(',') : null}
            required>
              <Validator rules={[{required: true, type:'email', message: '请输入正确的邮箱地址'}]} trigger={this.state.emailValidateMethod}>
                <Input type="email" name="email" id="email" value={formData.email} placeholder="onBlur 与 onChange 相结合" onBlur={this.handleEmailInputBlur} onFocus={this.handleEmailInputFocus} />
              </Validator>
          </FormItem>

          <FormItem
            label="密码:"
            id="password"
            labelCol={{span: 7}}
            wrapperCol={{span: 12}}
            validateStatus={this.renderValidateStyle('passwd')}
            hasFeedback
            help={status.passwd.errors ? status.passwd.errors.join(',') : null}
            required>
              <Validator rules={[{required: true, whitespace: true, message: '请填写密码'}, {validator: this.checkPass}]}>
                <Input name="passwd" id="password" type="password" onContextMenu={noop} onPaste={noop} onCopy={noop} onCut={noop} autoComplete="off" value={formData.passwd}/>
              </Validator>
          </FormItem>

          <FormItem
            label="确认密码:"
            id="password2"
            labelCol={{span: 7}}
            wrapperCol={{span: 12}}
            validateStatus={this.renderValidateStyle('rePasswd')}
            hasFeedback
            help={status.rePasswd.errors ? status.rePasswd.errors.join(',') : null}
            required>
              <Validator rules={[{
                required: true,
                whitespace: true,
                message: '请再次输入密码'
              }, {validator: this.checkPass2}]}>
                <Input name="rePasswd" id="password2" type="password" onContextMenu={noop} onPaste={noop} onCopy={noop} onCut={noop} autoComplete="off" value={formData.rePasswd} placeholder="两次输入密码保持一致"/>
              </Validator>
          </FormItem>

          <FormItem
            label="备注:"
            id="textarea"
            labelCol={{span: 7}}
            wrapperCol={{span: 12}}
            validateStatus={this.renderValidateStyle('textarea')}
            help={status.textarea.errors ? status.textarea.errors.join(',') : null}
            required>
              <Validator rules={[{required: true, message: '真的不打算写点什么吗?'}]}>
                <Input type="textarea" placeholder="随便写" id="textarea" name="textarea" value={formData.textarea} />
              </Validator>
          </FormItem>

          <FormItem
            wrapperCol={{span: 12, offset: 7}} >
            <Button type="primary" onClick={this.handleSubmit}>确定</Button>
            &nbsp;&nbsp;&nbsp;
            <Button type="ghost" onClick={this.handleReset}>重置</Button>
          </FormItem>
        </Validation>
      </Form>
    );
  }
});

ReactDOM.render(<Demo />, mountNode);

基本的表单校验例子。

每个表单域要声明 name 属性作为校验的标识,可通过其 isValidatingerrors 属性判断是否处于校验中、是否校验不通过状态,具体可参见 用户名 校验。

表单提交的时候,通过 Validation 的 validate 方法判断是否所有表单域校验通过(isValid 会作为回调函数的参数传入)。

注意: ES6 语法 不支持 mixins

import { Validation, Button, Form, Input, Row, Col } from 'antd';
import classNames from 'classnames';
const Validator = Validation.Validator;
const FormItem = Form.Item;

function noop() {
  return false;
}

const Demo = React.createClass({
  mixins: [Validation.FieldMixin],

  getInitialState() {
    return {
      status: {
        pass: {},
        rePass: {}
      },
      formData: {
        pass: undefined,
        rePass: undefined
      },
      passBarShow: false, // 是否显示密码强度提示条
      rePassBarShow: false,
      passStrength: 'L', // 密码强度
      rePassStrength: 'L'
    };
  },

  handleSubmit(e) {
    e.preventDefault();
    const validation = this.refs.validation;
    validation.validate((valid) => {
      if (!valid) {
        console.log('error in form');
        return;
      } else {
        console.log('submit');
      }
      console.log(this.state.formData);
    });
  },

  handleReset(e) {
    this.refs.validation.reset();
    this.setState(this.getInitialState());
    e.preventDefault();
  },

  renderValidateStyle(item) {
    const formData = this.state.formData;
    const status = this.state.status;

    const classes = classNames({
      'error': status[item].errors,
      'validating': status[item].isValidating,
      'success': formData[item] && !status[item].errors && !status[item].isValidating
    });

    return classes;
  },

  getPassStrenth(value, type) {
    if (value) {
      let strength;
      // 密码强度的校验规则自定义,这里只是做个简单的示例
      if (value.length < 6) {
        strength = 'L';
      } else if (value.length <= 9) {
        strength = 'M';
      } else {
        strength = 'H';
      }
      if (type === 'pass') {
        this.setState({ passBarShow: true, passStrength: strength });
      } else {
        this.setState({ rePassBarShow: true, rePassStrength: strength });
      }
    } else {
      if (type === 'pass') {
        this.setState({ passBarShow: false });
      } else {
        this.setState({ rePassBarShow: false });
      }
    }
  },

  checkPass(rule, value, callback) {
    this.getPassStrenth(value, 'pass');

    if (this.state.formData.pass) {
      this.refs.validation.forceValidate(['rePass']);
    }

    callback();
  },

  checkPass2(rule, value, callback) {
    this.getPassStrenth(value, 'rePass');

    if (value && value !== this.state.formData.pass) {
      callback('两次输入密码不一致!');
    } else {
      callback();
    }
  },

  renderPassStrengthBar(type) {
    const strength = type === 'pass' ? this.state.passStrength : this.state.rePassStrength;
    const classSet = classNames({
      'ant-pwd-strength': true,
      'ant-pwd-strength-low': strength === 'L',
      'ant-pwd-strength-medium': strength === 'M',
      'ant-pwd-strength-high': strength === 'H'
    });
    const level = {
      L: '低',
      M: '中',
      H: '高'
    };

    return (
      <div>
        <ul className={classSet}>
          <li className="ant-pwd-strength-item ant-pwd-strength-item-1"></li>
          <li className="ant-pwd-strength-item ant-pwd-strength-item-2"></li>
          <li className="ant-pwd-strength-item ant-pwd-strength-item-3"></li>
          <span className="ant-form-text">
            {level[strength]}
          </span>
        </ul>
      </div>
    );
  },

  render() {
    const formData = this.state.formData;
    const status = this.state.status;

    return (
      <Form horizontal>
        <Validation ref="validation" onValidate={this.handleValidate}>
          <Row>
            <Col span="18">
              <FormItem
                label="密码:"
                id="confirmPass"
                labelCol={{span: 6}}
                wrapperCol={{span: 18}}
                validateStatus={this.renderValidateStyle('pass')}
                help={status.pass.errors ? status.pass.errors.join(',') : null}
                required>
                  <Validator rules={[{required: true, whitespace: true, message: '请填写密码'}, {validator: this.checkPass}]} trigger="onChange">
                    <Input name="pass" id="confirmPass" type="password" onContextMenu={noop} onPaste={noop} onCopy={noop} onCut={noop} autoComplete="off" value={formData.pass}/>
                  </Validator>
              </FormItem>
            </Col>
            <Col span="6">
              {this.state.passBarShow ? this.renderPassStrengthBar('pass') : null}
            </Col>
          </Row>

          <Row>
            <Col span="18">
              <FormItem
                label="确认密码:"
                id="confirmPass2"
                labelCol={{span: 6}}
                wrapperCol={{span: 18}}
                validateStatus={this.renderValidateStyle('rePass')}
                help={status.rePass.errors ? status.rePass.errors.join(',') : null}
                required>
                  <Validator rules={[{
                    required: true,
                    whitespace: true,
                    message: '请再次输入密码'
                  }, {validator: this.checkPass2}]}>
                    <Input name="rePass" id="confirmPass2" type="password" onContextMenu={noop} onPaste={noop} onCopy={noop} onCut={noop} autoComplete="off" value={formData.rePass}/>
                    </Validator>
              </FormItem>
            </Col>
            <Col span="6">
              {this.state.rePassBarShow ? this.renderPassStrengthBar('rePass') : null}
            </Col>
          </Row>

          <FormItem
            wrapperCol={{span: 12, offset: 6}}
            required>
            <Button type="primary" onClick={this.handleSubmit}>确定</Button>
            &nbsp;&nbsp;&nbsp;
            <Button type="ghost" onClick={this.handleReset}>重置</Button>
          </FormItem>
        </Validation>
      </Form>
    );
  }
});

ReactDOM.render(<Demo />, mountNode);
.ant-pwd-strength {
  display: inline-block;
  margin-left: 8px;
  line-height: 32px;
  height: 32px;
  vertical-align: middle;
}

.ant-pwd-strength-item {
  float: left;
  margin-right: 1px;
  margin-top: 12px;
  width: 19px;
  height: 8px;
  line-height: 8px;
  list-style: none;
  background-color: #f3f3f3;
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.ant-pwd-strength-item-1 {
  border-top-left-radius: 6px;
  border-bottom-left-radius: 6px;
}

.ant-pwd-strength-item-2 {
  width: 20px;
}

.ant-pwd-strength-item-3 {
  border-top-right-radius: 6px;
  border-bottom-right-radius: 6px;
  margin-right: 8px;
}

.ant-pwd-strength-low .ant-pwd-strength-item-1, .ant-pwd-strength-medium .ant-pwd-strength-item-1, .ant-pwd-strength-high .ant-pwd-strength-item-1 {
  background-color: #FAC450;
}

.ant-pwd-strength-medium .ant-pwd-strength-item-2, .ant-pwd-strength-high .ant-pwd-strength-item-2 {
  background-color: rgba(135, 208, 104, .6);
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#9987D068,endColorstr=#9987D068);
}

.ant-pwd-strength-high .ant-pwd-strength-item-3 {
  background-color: #87D068;
}

密码校验实例。

这里使用了 validation 的 forceValidate(fields, callback) 方法,在对第一次输入的密码进行校验时会触发二次密码的校验。

import {Validation, Select, Radio, Button, DatePicker, InputNumber, Form} from 'antd';
const Validator = Validation.Validator;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;

function cx(classNames) {
  if (typeof classNames === 'object') {
    return Object.keys(classNames).filter(function(className) {
      return classNames[className];
    }).join(' ');
  } else {
    return Array.prototype.join.call(arguments, ' ');
  }
}

const Demo = React.createClass({
  mixins: [Validation.FieldMixin],

  getInitialState() {
    return {
      status: {
        select: {},
        multiSelect: {},
        radio: {},
        birthday: {},
        primeNumber: {}
      },
      formData: {
        select: undefined,
        multiSelect: undefined,
        radio: undefined,
        birthday: null,
        primeNumber: 9
      }
    };
  },

  renderValidateStyle(item) {
    const formData = this.state.formData;
    const status = this.state.status;

    const classes = cx({
      'error': status[item].errors,
      'validating': status[item].isValidating,
      'success': formData[item] && !status[item].errors && !status[item].isValidating
    });

    return classes;
  },

  handleReset(e) {
    this.refs.validation.reset();
    this.setState(this.getInitialState());
    e.preventDefault();
  },

  handleSubmit(e) {
    e.preventDefault();
    this.setState({
      isEmailOver: true
    });
    const validation = this.refs.validation;
    validation.validate((valid) => {
      if (!valid) {
        console.log('error in form');
        return;
      } else {
        console.log('submit');
      }
      console.log(this.state.formData);
    });
  },

  checkBirthday(rule, value, callback) {
    if (value && value.getTime() >= Date.now()){
      callback(new Error('你不可能在未来出生吧!'));
    } else {
      callback();
    }
  },

  checkPrime(rule, value, callback) {
    if (value !== 11) {
      callback(new Error('8~12之间的质数明明是11啊!'));
    } else {
      callback();
    }
  },

  render() {
    const formData = this.state.formData;
    const status = this.state.status;

    return (
      <Form horizontal>
        <Validation ref="validation" onValidate={this.handleValidate}>
          <FormItem
            label="国籍:"
            id="select"
            labelCol={{span: 7}}
            wrapperCol={{span: 12}}
            validateStatus={this.renderValidateStyle('select')}
            help={status.select.errors ? status.select.errors.join(',') : null}
            required>
              <Validator rules={[{required: true, message: '请选择您的国籍'}]}>
                <Select size="large" placeholder="请选择国家" style={{width: '100%'}} name="select" value={formData.select}>
                  <Option value="china">中国</Option>
                  <Option value="use">美国</Option>
                  <Option value="japan">日本</Option>
                  <Option value="korean">韩国</Option>
                  <Option value="Thailand">泰国</Option>
                </Select>
              </Validator>
          </FormItem>

          <FormItem
            label="喜欢的颜色:"
            labelCol={{span: 7}}
            wrapperCol={{span: 12}}
            validateStatus={this.renderValidateStyle('multiSelect')}
            help={status.multiSelect.errors ? status.multiSelect.errors.join(',') : null}
            required>
            <Validator rules={[{required: true, message: '请选择您喜欢的颜色', type: 'array'}]}>
              <Select multiple size="large" placeholder="请选择颜色" style={{width: '100%'}} name="multiSelect" value={formData.multiSelect}>
                <Option value="red">红色</Option>
                <Option value="orange">橙色</Option>
                <Option value="yellow">黄色</Option>
                <Option value="green">绿色</Option>
                <Option value="blue">蓝色</Option>
              </Select>
            </Validator>
          </FormItem>

          <FormItem
            label="性别:"
            id="radio"
            labelCol={{span: 7}}
            wrapperCol={{span: 12}}
            validateStatus={this.renderValidateStyle('radio')}
            help={status.radio.errors ? status.radio.errors.join(',') : null}
            required>
              <Validator rules={[{required: true, message: '请选择您的性别'}]}>
                <RadioGroup name="radio" value={formData.radio}>
                  <Radio value="male"></Radio>
                  <Radio value="female"></Radio>
                </RadioGroup>
              </Validator>
          </FormItem>

          <FormItem
            label="生日:"
            id="birthday"
            labelCol={{span: 7}}
            wrapperCol={{span: 12}}
            validateStatus={this.renderValidateStyle('birthday')}
            help={status.birthday.errors ? status.birthday.errors.join(',') : null}
            required>
              <Validator rules={[{
                required: true,
                type: 'date',
                message: '你的生日是什么呢?'
              }, {validator: this.checkBirthday}]}>
                <DatePicker name="birthday" value={formData.birthday} />
              </Validator>
          </FormItem>

          <FormItem
            label="8~12间的质数:"
            id="primeNumber"
            labelCol={{span: 7}}
            wrapperCol={{span: 12}}
            validateStatus={this.renderValidateStyle('primeNumber')}
            help={status.primeNumber.errors ? status.primeNumber.errors.join(',') : null}
            required>
              <Validator rules={[{validator: this.checkPrime}]}>
                <InputNumber name="primeNumber" min={8} max={12} value={formData.primeNumber} />
              </Validator>
          </FormItem>

          <FormItem
            wrapperCol={{span: 12, offset: 7}} >
            <Button type="primary" onClick={this.handleSubmit}>确定</Button>
            &nbsp;&nbsp;&nbsp;
            <Button type="ghost" onClick={this.handleReset}>重置</Button>
          </FormItem>
        </Validation>
      </Form>
    );
  }
});

ReactDOM.render(<Demo />, mountNode);

提供以下组件表单域的校验。

Select Radio DatePicker InputNumber