Form validation
Now let’s implement simple form validation using regular expressions — let’s ensure that the first name is at least three characters long, and contains only letters.
We will add another event handler for the onBlur
event —it will fire whenever the user leaves the input. We will also add another property to the state — firstNameError
. And then we’ll display the validation error right under the input (if errors are present).
State
First, we’ve added a firstNameError
property to the state:
state = {
...
firstNameError: "",
};
Validation function
The validation itself is happening in the validateName
arrow function above. It simply tests the input name against the regular expression:
validateName = name => {
const regex = /[A-Za-z]{3,}/;
return !regex.test(name)
? "The name must contain at least three letters..."
: "";
}
If the validation fails, we return the validation error. If the validation succeeds, then we return an empty string (which signifies lack of error). We’re using JavaScript ternary expressions here to make the code terser.
onBlur event handler
Let’s take a look at the onBlur
event handler (fires whenever the user leaves the input):
onFirstNameBlur = () => {
const { firstName } = this.state;
const firstNameError = this.validateName( firstName );
return this.setState({ firstNameError });
};
Here we extract the firstName
from the state by using ES6 object destructuring syntax. The first line is equivalent to:
const firstName = this.state.firstName;
Then we run the validation function defined above with the firstName
, and then we set the firstNameError
state property with the error returned. If the validation failed, the firstNameError
will be set. If it succeeds, then it will be set to an empty string.
render
method
And now let’s take a look at the render()
method:
render() {
const { firstNameError, firstName} = this.state;
...
}
Here we’re once again using ES6 object destructuring to extract values from the state.
...
onBlur={this.onFirstNameBlur}
/>
This line assigns the onFirstNameBlur
function as the event handler for the onBlur
event.
{firstNameError &&{firstNameError}}
Here we’re using short circuit evaluation feature of JavaScript. The div containing the firstNameError
will be rendered only if the value itself is truthy.