尝试使用字段配置在 React-bootstrap 表单上进行输入验证
const TextInput = (props) => {
const [text, setText] = useState('');
const {
type,
colProps,
register,
errors,
fieldInfo,
...restProps
} = props;
const { label, name, value, validation } = fieldInfo || {};
const validatePattern = (input) =>{
const regex = new RegExp(validation?.pattern?.value);
return regex.test(input)
}
return (
<Form.Group as={Col} {...colProps} >
{label}
<Form.Control
type ={type}
name={name}
value={value}
defaultValue = {fieldInfo?.defaultValue ?fieldInfo?.defaultValue:''}
{...restProps}
{...register(name {
...validation
})}
isValid={validatePattern(value)}
/* tried doing this with onChange to track input but onChange doesnt fire... and value is always undefined */
/>
</Form.Group>
);
};
export default TextInput;
然后使用json配置来定义fieldInfo:
{
"type": "TEXT_INPUT",
"colProps": { "sm":"auto" },
"fieldInfo": {
"label": "Case Number",
"name": "caseNumber",
"validation" :{
"pattern": {
"value": "^[0-9]{8,12}$",
"message": "Input is Numeric, larger than 8, less than 13"
},
"required": {
"value": true,
"message": "Case number is required"
},
"maxLength": {
"value": 12,
"message": "Case number should be less than 13 chars."
}
}
}
}
required 和 maxLength 验证有效,但模式不会触发错误。我可以调试并看到它们为浏览器带来了信息 - 只是浏览器什么也不做。
如上所述,即使我尝试 useState 并捕获输入的值,validatePattern 也只能看到未定义的输入。
发布此内容后,我想我可以将 validate 函数和 onChange 函数传递到寄存器中。因此,为了工作,我更新了渲染中的寄存器函数并使用 useState 挂钩处理输入。
const Input = (props) => {
const[text, setText] = useState('');
const {
type,
colProps,
register,
errors,
fieldInfo,
...restProps
} = props;
const { label, name, value, validation } = fieldInfo || {};
const validatePattern = () =>{
if (validation?.pattern?.value && text){
const isValid = new RegExp(validation?.pattern?.value).test(text);
return isValid? null: validation?.pattern?.message;
}
}
const handleInput = (e) =>{
e.preventDefault();
setText(e.target.value);
}
return (
<Form.Group as={Col} {...colProps} >
{label}
<Form.Control
type ={type}
name={name}
value={value}
defaultValue = {fieldInfo?.defaultValue ?fieldInfo?.defaultValue:''}
{...restProps}
{...register(name {
...validation,
onChange: handleInput,
validate: validatePattern
})}
key={input+name}
/>
</Form.Group>
);
};
export default Input;
然后,我可以保留 json 配置,让团队使用它来设置正则表达式。其他验证仍然继续有效。