Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-hook-form Controller onBlur callback not triggering validation

Want to trim an input field when user onBlurs.

    <Controller 
    ...
    onBlur={([e]) => {
    const { value } = e.target;
    const trimmedValue = value.trim();
    console.log('trim here: ', value, value.length, trimmedValue.length);
    if (trimmedValue === '') {
    console.log('error!!!');
    return trimmedValue;
    }
    return trimmedValue;
    }} />

Rule:

rules={{
 pattern: {
 value: new RegExp(firstName.validationString, 'i'),
message: 'First name must be 2 - 100 characters with no numbers.',
},
required: firstName.mandatory && 'Must fill in first name',
}}

The function is triggered and reaching the if-statement. But is not triggering an error even though I have a rule set as required.

like image 576
papa-ogen Avatar asked Jun 30 '26 20:06

papa-ogen


1 Answers

use this in your register or controller

validate: (value) => { return !!value.trim()}

Take a look here: https://github.com/react-hook-form/react-hook-form/issues/1650

like image 174
utkarsh Avatar answered Jul 02 '26 13:07

utkarsh