常见的表单需要的校验------(必须为数字,多个ID以英文逗号或回车分隔,是否有重复,商品ID个数的限制)
<Form.Item
label="商品ID"
name="prodId"
rules={[
{ required: true, message: '请输入商品ID' },
{ pattern: /^d[d
,]*d*$/, message: '商品ID是纯数字,多个ID以英文逗号或回车分隔' },
{
validator: (_, values) => {
const prodIdSame = values?.toString().replace(/[
]/g, ',');
const idSame = prodIdSame?.split(',');
if (idSame && idSame?.length !== [...new Set(idSame)].length) {
return Promise.reject(new Error('商品ID有重复'));
} if (idSame?.length > 1000) {
return Promise.reject(new Error('单次最多提交1000个'));
}
return Promise.resolve();
},
},
]}
>
<TextArea rows={4} placeholder="请输入商品 ID,多个商品 ID 用英文逗号分隔,单次最多提交 1000个" disabled={isEdit} />
</Form.Item>
这里表单有气泡框 点击气泡的弹出框才可以提交 所以 不能直接用表单的onfinish了 因此给”提交“按钮添加了onClick事件
<Form.Item>
{
productInfo.length > 0 ? (
<Popconfirm
className="popconfirm-sty"
visible={showPopconfirm}
placement="top"
title={this.renderTitile}
onConfirm={() => this.deploy(formData)}
onCancel={this.handleCancel}
okText="确认"
cancelText="取消"
>
<Button type="primary" onClick={this.handleSubmit}>提交</Button>
</Popconfirm>
) : <Button type="primary" onClick={this.handleSubmit}>提交</Button>
}
</Form.Item>
这里表单提交的时候一定要用validateFields()去校验
handleSubmit = () => {
const { current } = this.formRef;
current.validateFields().then((values) => {
const { getProductInfo } = this.props;
const { isEdit } = this.state;
const params = getUrlkey(window.location.href);
this.setState({
formData: values,
});
const idStr = isEdit ? params.prodId : values?.prodId.split(',')[0];
getProductInfo({ data: { prodId: idStr || params.prodId } }).then((res) => {
if (res?.data?.length > 0) {
this.setState({
showPopconfirm: true,
});
} else {
this.setState({
showPopconfirm: false,
});
}
});
}).catch();
}