Ant Design Form 表单:自定义输入框校验图标
可以通过 Ant Design 的 Form 组件配合自定义的校验规则和图标来实现这个需求。具体步骤如下:
- 导入 Ant Design 的 Form 和 Input 组件,并导入自定义的成功和失败图标:
import { Form, Input } from 'antd';
import { CheckCircleFilled, CloseCircleFilled } from '@ant-design/icons';
- 在 Form 组件中使用 getFieldDecorator 方法给输入框添加校验规则和自定义图标:
<Form>
<Form.Item>
{getFieldDecorator('username', {
rules: [
{ required: true, message: '请输入用户名' }, // 添加必填规则
// 添加自定义校验规则
{ validator: this.validateUsername }
],
})(<Input
placeholder='请输入用户名'
// 根据校验状态判断是否显示图标
suffix={getFieldError('username') ? <CloseCircleFilled style={{ color: 'red' }} /> : (isFieldTouched('username') && !getFieldError('username')) && <CheckCircleFilled style={{ color: 'green' }} />}
/>)}
</Form.Item>
</Form>
- 编写自定义的校验规则 validateUsername,根据规则返回不同的校验结果:
validateUsername = (rule, value, callback) => {
// 校验规则
if (value.length < 6) {
callback('用户名长度不能小于6位');
} else {
callback(); // 校验通过
}
}
这样,当输入框内容满足校验规则时,会显示自定义的成功图标(绿色),不满足校验规则时,会显示自定义的失败图标(红色)。
完整代码示例:
import React, { Component } from 'react';
import { Form, Input } from 'antd';
import { CheckCircleFilled, CloseCircleFilled } from '@ant-design/icons';
class MyForm extends Component {
validateUsername = (rule, value, callback) => {
// 校验规则
if (value.length < 6) {
callback('用户名长度不能小于6位');
} else {
callback(); // 校验通过
}
}
render() {
const { getFieldDecorator, getFieldError, isFieldTouched } = this.props.form;
return (
<Form>
<Form.Item>
{getFieldDecorator('username', {
rules: [
{ required: true, message: '请输入用户名' }, // 添加必填规则
// 添加自定义校验规则
{ validator: this.validateUsername }
],
})(<Input
placeholder='请输入用户名'
// 根据校验状态判断是否显示图标
suffix={getFieldError('username') ? <CloseCircleFilled style={{ color: 'red' }} /> : (isFieldTouched('username') && !getFieldError('username')) && <CheckCircleFilled style={{ color: 'green' }} />}
/>)}
</Form.Item>
</Form>
);
}
}
const WrappedMyForm = Form.create()(MyForm);
export default WrappedMyForm;
原文地址: https://www.cveoy.top/t/topic/cd4e 著作权归作者所有。请勿转载和采集!