相信各位朋友在使用react + ant design的form表单时候,经常需要做一些表单信息的必填校验的逻辑,表单有受控组件跟非受控组件的区分。
在受控组件中通常情况下,我们只需要按照下面的配置即可
rules: [{ required: true, message: '请至少选择一个业务' }]
例子:
<FormItem label="交接原因" {...itemLayout.wholeLine}>
{getFieldDecorator('handoverReason', {
initialValue: '',
rules: [{ required: true, message: '请输入交接原因' }]
})(
<AInputTextarea rows={2} maxLength={50} placeholder="请输入交接原因,最多50个字符"/>
)}
</FormItem>
在非受控组件中,或者说我们的formItem要实现一些特殊的需求时,这个时候可能上面的简单配置没有办法满足我们的需求。
需求:我们的formItem是一个按钮,点击按钮唤起modal弹窗,通过选择数据以tag标签的形式进行回填,并且可以删除回填的数据。
目标:我们想要在删除回填的数据的时候,也能触发表单的必填信息校验。
// FormItem布局代码
<FormItem label="业务范围" {...itemLayout.wholeLine}>
{getFieldDecorator('businessScope', {
initialValue: undefined,
rules: [{ required: true, message: '请至少选择一个业务' }]
})(
<div>
<AButton onClick={this.openSelectBuinessModal} style={{height: '28px', lineHeight: '28px'}}>选择</AButton>
{
selectScopeTypeList.length > 0
? <span style={{color: '#E9E9E9', marginLeft: '14px', fontSize: '18px', lineHeight: '26px'}}>|</span>
: null
}
{
selectScopeTypeList.map(item=>(
<Tag className='select-scope-item-tag' closable onClose={()=>this.closeSelectScopeItem(item)}>{item == 'customer' ? '客户' : null}</Tag>
))
}
</div>
)}
</FormItem>
// 删除回填数据的方法
closeSelectScopeItem = (type) =>{
const {selectScopeTypeList, selectScopeDataList} = this.state;
this.props.form.setFields({
businessScope: {
value: selectScopeTypeList.filter(item=> item != type).join(','),
errors: [new Error('请至少选择一个业务')],
}
})
this.setState({
selectScopeTypeList: selectScopeTypeList.filter(item=> item != type),
selectScopeDataList: selectScopeDataList.filter(item=> item.type != type)
})
}
在上面的方法中,在删除回填数据的时候,重新修改了FormItem的businessScope字段值,并对errors报错提示进行赋值处理。除了上面方法之外,已下方法也能实现我们效果,即:删除回填的数据后对form表单校验。
this.props.form.validateFields(['businessScope'], (err, values) => {
if (!err) {
// 如果没有校验错误,可以执行其他逻辑
}
});