# 表单校验 - order: 11 基本的表单校验例子。 --- ````jsx import { Button, Form, Input } from 'antd'; const createForm = Form.create; const FormItem = Form.Item; function noop() { return false; } class BasicDemo extends React.Component { getValidateStatus(field) { const { isFieldValidating, getFieldError, getFieldValue } = this.props.form; if (isFieldValidating(field)) { return 'validating'; } else if (!!getFieldError(field)) { return 'error'; } else if (getFieldValue(field)) { return 'success'; } } handleReset(e) { e.preventDefault(); this.props.form.resetFields(); } handleSubmit(e) { e.preventDefault(); this.props.form.validateFields((errors, values) => { if (!!errors) { console.log('Errors in form!!!'); return; } console.log('Submit!!!'); console.log(values); }); } userExists(rule, value, callback) { if (!value) { callback(); } else { setTimeout(() => { if (value === 'JasonWood') { callback([new Error('抱歉,该用户名已被占用。')]); } else { callback(); } }, 800); } } checkPass(rule, value, callback) { const { validateFields } = this.props.form; if (value) { validateFields(['rePasswd']); } callback(); } checkPass2(rule, value, callback) { const { getFieldValue } = this.props.form; if (value && value !== getFieldValue('passwd')) { callback('两次输入密码不一致!'); } else { callback(); } } render() { const { getFieldProps, getFieldError, isFieldValidating } = this.props.form; const nameProps = getFieldProps('name', { rules: [ { required: true, min: 5, message: '用户名至少为 5 个字符' }, { validator: this.userExists }, ], }); const emailProps = getFieldProps('email', { validate: [{ rules: [ { required: true }, ], trigger: 'onBlur', }, { rules: [ { type: 'email', message: '请输入正确的邮箱地址' }, ], trigger: ['onBlur', 'onChange'], }] }); const passwdProps = getFieldProps('passwd', { rules: [ { required: true, whitespace: true, message: '请填写密码' }, { validator: this.checkPass.bind(this) }, ], }); const rePasswdProps = getFieldProps('rePasswd', { rules: [{ required: true, whitespace: true, message: '请再次输入密码', }, { validator: this.checkPass2.bind(this), }], }); const textareaProps = getFieldProps('textarea', { rules: [ { required: true, message: '真的不打算写点什么吗?' }, ], }); const formItemLayout = { labelCol: { span: 7 }, wrapperCol: { span: 12 }, }; return (
); } } BasicDemo = createForm()(BasicDemo); ReactDOM.render(