perscrew / react-native-form-validator

React native library to validate form fields

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

isFieldInError and getErrorsInField doesn't work and custom messages

Skt-Alvaro opened this issue · comments

Hello, I'm trying to make conditionals with isFieldInError and getErrorsInField, but it returned me false and an empty array respectively even having errors, this is my code, I'm doing like a reusable component.

function RegisterForm({data}) {
  const [field, setField] = useState('');
  const [value] = useDebounce(field, 1000);

  const {validate, isFieldInError, getErrorsInField, getErrorMessages} =
    useValidation({
      state: {field},
    });

  const _validateForm = () => {
    validate({
      field: data.rules,
    });
  };

  React.useEffect(() => {
    if (value.length !== 0) {
      _validateForm();
    }
  }, [value]);

  return (
    <View style={tailwind('px-8')}>
      <TextInput
        placeholder={data.placeholder}
        style={[
          tailwind('text-black p-0 text-xl pb-1 flex-row'),
          {
            borderBottomWidth: 1,
            borderBottomColor: '#808080',
          },
        ]}
        onChangeText={text => setField(text)}
        value={field}
      />
      <Text>{getErrorMessages()}</Text>
      <TouchableOpacity onPress={() => _validateForm()}>
        <Text>auwhdauywd</Text>
      </TouchableOpacity>
    </View>
  );
}

And I want to use custom messages but I don't know how, please help me, thank you

Custom messages, local language, and labels should be passed as parameters to your component.
Example in react navigation v6 (with react navigation) for

Changing the local language :

<Stack.Screen name="Home">
          {props => <MyComponent {...props} deviceLocale='fr' />}
 </Stack.Screen>

Passing custom messages :

import {customMessages} from './shared/errorMessages';


<Stack.Screen name="Home">
          {props => <MyComponent {...props} messages={customMessages} />}
</Stack.Screen>

You can create your own custom messages const and customize message languages as follow :

export const customMessages= {
    en: {
        numbers: 'The field "{0}" must be a valid number.',
        email: 'The field "{0}" must be a valid email address.',
        required: 'The field "{0}" is mandatory.',
        date: 'The field "{0}" must be a valid date ({1}).',
        minlength: 'The field "{0}" length must be greater than {1}.',
        maxlength: 'The field "{0}" length must be lower than {1}.',
        equalPassword: 'Passwords are different.',
        hasUpperCase: 'The field "{0}" must contain a upper case.',
        hasLowerCase: 'The field "{0}" must contain a lower case.',
        hasNumber: 'The field "{0}" must contain a number.',
        hasSpecialCharacter: 'The field "{0}" must contain a special character.',
    }
    ...
    // you can add your local (fr, es...)
}