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.
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;