React Forms — Frontend Validations
This time we will making front end validations for our form we created last time.
https://medium.com/@natey37/react-forms-class-vs-functional-624b71beda5c
At the bottom of our form we simply add a button,
<button>Submit</button>
And then add an onSubmit function to our form at the top.
We will event.preventDefault() so that our form doesn’t refresh the page each time we press submit. Now we want to make some validations for our form which will get run when someone clicks submit.
First, we will create a new state called errors and set it to an empty object. We will create a handleValidation function which will check our inputs. In this we will set an empty object ‘errors’ that will hold all of the errors we may find. We declare an isFormValid function, which we will return at the end of our handleValidtion function. If our form is valid we will return true and if it isn’t we will return false and show our errors.
Let’s check our first input:
We check to see if our form contains a value for the key ‘name’. If it doesn’t, then we set our isFormValid to false and we add a new error to our errors object, letting the user know that the input cannot be empty. Then we check to make sure the name input is not undefined. If it isn’t, then we will use a regex to check if the name input only contains letters. If it contains anything other than letters, then our form is not valid and we add an error telling the user that the name must include only letters.
We do the same thing for the email:
We could use a more rigid regex to check for a valid email address, but we will go with something relatively simple.
This makes sure that the format is string@string.string
Next:
Here we make a regex check for digits only, and then we also check to make sure the user only entered a digit 5 numbers long.
Next we will add validations for our date. For our purposes let’s assume we are planning to schedule something, so we want users to choose a date that is at least a week in the future.
We check to make sure that the date chosen is in the future by 7 days. If it is not it will let the user know they need to pick a date a week from todays date.
At the end of our form we will want to set our current state errors with the new errors we just found and we want to return if our form is valid or not.
Then we can add our errors to our form. For each input we can show the corresponding error underneath.
Here is our finished handleValidation function:
Let’s style our error messages so they are more obvious to the user.
And give our button a little character!
Now, when our form has valid inputs and we press the submit button, our form closes.
For now we are not saving our inputs, tune in next time we will store our submitted forms so we can access them later.