# 基本 - order: 0 基本的表单校验栗子。 每个表单域要声明 `name` 属性作为校验的标识,可通过其 `isValidating` `errors` 属性判断是否处于校验中、是否校验不通过状态,具体可参见 **用户名** 校验。 表单提交的时候,通过 Validation 的 validate 方法判断是否所有表单域校验通过(isValid 会作为回调函数的参数传入)。 --- ````jsx var Validation = antd.Validation; var Validator = Validation.Validator; var Select = antd.Select; var Option = Select.Option; var Radio = antd.Radio; var RadioGroup = antd.RadioGroup; 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, ' '); } } var Form = React.createClass({ mixins: [Validation.FieldMixin], getInitialState() { return { status: { email: {}, name: {}, select: {}, radio: {}, passwd: {}, rePasswd: {}, textarea: {} }, formData: { email: undefined, name: undefined, select: undefined, radio: undefined, passwd: undefined, rePasswd: undefined, textarea: undefined } }; }, validateStyle(item, hasFeedback=true) { var formData = this.state.formData; var status = this.state.status; var classes = cx({ 'has-feedback': hasFeedback, 'has-error': status[item].errors, 'is-validating': status[item].isValidating, 'has-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(); var 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 === 'yiminghe') { callback([new Error('抱歉,该用户名已被占用。')]); } else { callback(); } }, 1000); } }, checkPass(rule, value, callback) { if (this.state.formData.passwd) { this.refs.validation.forceValidate(['rePasswd']); } callback(); }, checkPass2(rule, value, callback) { if (value !== this.state.formData.passwd) { callback('两次输入密码不一致!'); } else { callback(); } }, render() { var formData = this.state.formData; var status = this.state.status; return (
{status.name.isValidating ?
正在校验中...
: null} {status.name.errors ?
{status.name.errors.join(',')}
: null}
{status.email.errors ?
{status.email.errors.join(',')}
: null}
{status.select.errors ?
{status.select.errors.join(',')}
: null}
{status.radio.errors ?
{status.radio.errors.join(',')}
: null}
{status.passwd.errors ?
{status.passwd.errors.join(',')}
: null}
{status.rePasswd.errors ?
{status.rePasswd.errors.join(', ')}
: null}
{status.textarea.errors ?
{status.textarea.errors.join(',')}
: null}
    重 置
); } }); React.render(
, document.getElementById('components-validation-demo-basic')); ````