英文:
Is it possible to implement delayed validation for an control in react-form-hook?
问题
我有一个自定义验证用于一个输入字段,
模式: "onChange"
自定义验证是检查用户输入文本是否存在于字符串数组中,
假设我的数组大小增加,性能将受到影响(因为验证会在onChange触发)。
所以,我的问题是,是否可能在用户停止输入后的3秒内触发此自定义验证。
或者任何其他创造性的解决方案都会有所帮助,
FYI:我还有其他验证与自定义验证一起使用。
使用:MUI
库:react-form-hook
谢谢
我目前使用mode:"onBlur"作为一种解决方法。
英文:
I have a custom validation for an Input field,
mode: "onChange"
Custom validation is to check if the user input text is present in an array of string,
Suppose my array size increases, performancce will be hit (since validation triggers for onChange)
So, my question is , if it is possible to trigger this custom validation, 3 seconds from the moment user stops typing.
or any other create solution would be helpful,
FYI: I have other validation along with the custom validation.
Using : MUI
Library: react-form-hook
Thank You
I am currently using mode:"onBlur" as a workaround.
答案1
得分: 1
如果您熟悉使用lodash:
import React, { useState } from 'react';
import _ from 'lodash'; // 导入 Lodash 库(或使用您自己的 debounce 实现)
const MyComponent = () => {
const [inputValue, setInputValue] = useState('');
// 您的自定义验证函数
const customValidation = (value) => {
const arrayOfStrings = ['apple', 'banana', 'orange']; // 您的字符串数组
return arrayOfStrings.includes(value);
};
// 防抖验证函数
const debouncedValidation = _.debounce((value) => {
// 在此执行您的自定义验证
const isValid = customValidation(value);
// 处理验证结果(例如,更新表单状态,显示错误等)
console.log(`验证结果: ${isValid}`);
}, 3000); // 在触发验证之前等待 3 秒
const handleInputChange = (event) => {
const { value } = event.target;
setInputValue(value);
// 使用最新值触发防抖验证函数
debouncedValidation(value);
};
return (
<input
type="text"
value={inputValue}
onChange={handleInputChange}
// 从 MUI 库中添加其他所需的输入组件属性
/>
);
};
export default MyComponent;
英文:
If you are comfortable using lodash:
import React, { useState } from 'react';
import _ from 'lodash'; // Import Lodash library (or use your own debounce implementation)
const MyComponent = () => {
const [inputValue, setInputValue] = useState('');
// Your custom validation function
const customValidation = (value) => {
const arrayOfStrings = ['apple', 'banana', 'orange']; // Your array of strings
return arrayOfStrings.includes(value);
};
// Debounced validation function
const debouncedValidation = _.debounce((value) => {
// Perform your custom validation here
const isValid = customValidation(value);
// Handle the validation result (e.g., update form state, show errors, etc.)
console.log(`Validation result: ${isValid}`);
}, 3000); // Wait for 3 seconds before triggering the validation
const handleInputChange = (event) => {
const { value } = event.target;
setInputValue(value);
// Trigger the debounced validation function with the latest value
debouncedValidation(value);
};
return (
<input
type="text"
value={inputValue}
onChange={handleInputChange}
// Add other props needed for your Input component from MUI library
/>
);
};
export default MyComponent;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论