写在validator中应该怎么做,每个输入框都是单独的formItem
时间: 2024-11-22 19:45:06 浏览: 11
Hibernate Validator 6.1.7 中文文档
在Ant Design的Validator中,如果你需要为每个单独的FormItem(如输入框)编写验证规则,可以在FormItem的`rules`属性中直接定义。这是一个例子:
假设你有一个包含多个独立姓名输入框的情况:
```jsx
import { Form, Input, Button, message } from "antd";
import { validateFields } from "antd/lib/form";
const FormItem = Form.Item;
class YourComponent extends React.Component {
state = {
names: [],
errors: {}
};
handleInputChange = (index, value) => {
const newNames = [...this.state.names];
newNames[index] = value;
this.setState({ names: newNames });
// 验证当前输入名是否重复
if (newNames.some((name, i) => i !== index && name === value)) {
this.setState({ errors: { [`${index}`]: '名字不能重复' } });
} else {
this.setState({ errors: {} });
}
}
validateName = (values, callback) => {
const { names } = values;
let errorMessages = {};
for (let i = 0; i < names.length; i++) {
if (names.some((_, j) => j !== i && names[j] === names[i])) {
errorMessages[i] = '名字不能重复';
}
}
callback(errorMessages);
}
handleSubmit = (e) => {
e.preventDefault();
validateFields(this.form, this.validateName, (errors) => {
if (Object.keys(errors).length > 0) {
console.log('有错误', errors);
message.error(Object.values(errors).join(', '));
} else {
console.log('提交成功');
// 提交数据...
}
});
}
render() {
const { getFieldDecorator } = this.props.form;
return (
<Form ref={(c) => { this.form = c; }}>
{this.state.names.map((name, index) => (
<FormItem
{...getFieldDecorator(`name${index}`, {
rules: [{ required: true, message: '请输入名字' }],
initialValue: name,
onFieldChange: this.handleInputChange.bind(this, index)
})}
label="姓名"
>
<Input />
</FormItem>
))}
<Button type="primary" onClick={this.handleSubmit}>
提交
</Button>
</Form>
);
}
}
export default Form.create()(YourComponent);
```
在这个例子中,我们为每个`name`字段设置了独立的验证规则,当输入框改变时会实时检查是否重复,如果发现重复则更新错误信息。`handleSubmit`事件触发整个表单的验证。
阅读全文