Learning react-native at the moment, building a sign up form (using NativeBase components) and want to add validation to each input field.
The issue I am facing at present is that I am not seeing the specific error message come through, always falls back to the default
#SignUp.js
export const SignUp = ({navigation}) => {
const [errors, setErrors] = useState({});
const validateFirstName = () => {
if (formData.firstName === undefined) {
setErrors({
...errors,
name: 'First Name is required',
});
return false;
} else if (formData.firstName.length < 3) {
setErrors({
...errors,
name: 'First Name is too short',
});
return false;
}
return true;
};
// First Name Input Field
<FormControl isRequired isInvalid={'name' in errors}>
<FormControl.Label>First Name</FormControl.Label>
<Input value={firstName} onChangeText={firstName => setFirstName(firstName)}/>
{'name' in errors ?
<FormControl.ErrorMessage>Please enter a valid first name</FormControl.ErrorMessage>: ''
}
</FormControl>
}
So with this example lets say i submit an empty first name, I would expect to see the error message First Name is required
, but I get Please enter a valid first name
I do not seem to be accessing the error messages correctly, have i missed something ?
Thanks
You have missed one small thing. Just replace
<FormControl.ErrorMessage>Please enter a valid first name</FormControl.ErrorMessage>: ''
To
<FormControl.ErrorMessage>{errors.name}</FormControl.ErrorMessage>: ''
So, the component FormControl.ErrorMessage
will display its children when the component is in an invalid
state. You can read more about it here
I have created a snack, to show how to effectively use FormControl.