我正在使用一个教程react组件,其中的验证在组件中进行。我遇到问题,我只能进行一种验证,但是我想进行多次验证。
我的组件的渲染是
<Input
hintText={this.props.hinttext}
placeholder={this.props.placeholder}
value={this.state.value}
onChange={this.onChange}
/>
这是onChange方法
onChange = (evt) => {
const name= this.props.name;
const value = evt.target.value;
const error = this.props.validate ? this.props.validate(value) : false;
this.setState({value, error});
this.props.onChange({name, value, error});
}
现在我正在通过以下方法在表单中使用它
<Field
placeholder="Email"
name='email'
value={this.state.fields.email}
onChange={this.onInputChange}
validate={(val) => (isEmail(val) ? false: 'Invalid Email')}
/>
这将对电子邮件进行验证,而如果我需要另一种类型的验证,我可以像下面那样更改验证
validate={(val) => (val ? false : 'Name Required')}
所有工作正常,但是我想为一个字段定义两个验证,我注意到它是箭头函数,我应该添加多个值,但不确定如何执行,因为我在ES6中并不擅长。有任何建议。
答案 0 :(得分:1)
您可以尝试使用以下所需的验证来运行自定义验证器
function validator(val) {
this.error = [];
this.val = val;
this.isRequired = function(){
if (!this.val) {
this.error.push('This field is required');
}
return this;
}
this.isEmail = function() {
const filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (this.val && !filter.test(this.val)) {
this.error.push('Invalid Email');
}
return this;
}
return this;
}
并在validate属性中调用验证器
<Field
placeholder="Email"
name='email'
value={this.state.fields.email}
onChange={this.onInputChange}
validate={(val) => new validator(val).isRequired().isEmail().error}
/>