D
D
DimaSBB2020-10-21 19:16:35
React
DimaSBB, 2020-10-21 19:16:35

Input validation (returns false to string). How to fix?

The onChange event hangs on the input, according to which the handleChangeField function is executed when we write something to the input.
handleChangeField function:

const handleChangeField = (event) => {
        let value = event.target.value;
        
        setTitle(InputValidator(value, maxSize));
    }


inside this function, I call a validator (checking for the maximum number of entered elements and for special characters), which I put into a separate InputValidator function:

const InputValidator = (value, maxSize) => {
    let regExp = /[^а-яА-Яa-zA-Z0-9\s]/.test(value);
    
    if (regExp) return false;
    if (value.length > maxSize) return false;
    
    return value;
}

export default InputValidator;


The problem is that when the entered number of characters exceeded the allowable one or the entered character did not pass the regular check, then the string value "false" is entered into the input. How to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-10-21
@DimaSBB

Let the validator return true/false instead of valid_value/false:

const validator = (value, maxSize) =>
  !(/[^а-яА-Яa-zA-Z0-9\s]/.test(value) || value.length > maxSize);

Accordingly, call setTitle only if true:
if (validator(value, maxSize)) {
  setTitle(value);
}

If you still need the validator to return the value of the input, then it must receive not only the one that checks, but also some default correct one, so that there is something to return in case of a negative result of the check:
const validator = (defaultValue, value, maxSize) =>
  (/[^а-яА-Яa-zA-Z0-9\s]/.test(value) || value.length > maxSize)
    ? defaultValue
    : value;

setTitle(prevValue => validator(prevValue, value, maxSize));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question