Validating Forms in React Native

Pav Sidhu
2 min readFeb 12, 2017

--

validatejs.org

Update: September 2020

I wrote this article many years ago and since then things have changed. If you came across this article hoping to learn how to validate your forms I’d recommend using a better solution such as React Hook Form.

One of my favourite advantages of using React Native is that there are plenty of Javascript libraries already out there to help speed up your development, one of them being validate.js, which helps you to… validate your forms!

How Validate.js Works

Validate.js requires you to have a variable to hold your field validation rules such as presence checks, length checks etc. You can also create async and custom validators. Here is a basic example of what your rules could look like.

The structure is pretty self-explanatory other than you may have noticed that for all the error messages, I put ^ before them. The reason for this is because for some reason when you validate a field and there is an error, the error message will return the field name and the error message together such as Password Your password must be at least 5 characters. It’s a bit odd as to why this happens but my regex solution removes the field name from the error message.

My Wrapper to Validate Fields

I created a wrapper since I found that I would reuse a lot of the code between different forms. The function below takes the field name and its value and return the error message if there is one.

My Custom TextInput Component

Since I want every single TextInput to have validation, it would make sense to create a custom component which contained a TextInput and an error message. Here is a stripped down version:

An Example Form

The example below demonstrates how I validate forms in practice. I keep all the TextField values and error messages in the state. Every time the TextField is blurred, the value entered is validated and the error message in the state is updated.

When the button to send off the form is pressed, it calls a function to validate all the fields. If there are no errors, then the form can be submitted.

There you have it! That’s how I validate forms using React Native, I hope this helped.

This post is available on my blog: Validating Forms in React Native

In the comments: What is your method of validating forms with React Native?

Thanks for reading! If this helped you, click that ❤️ so that other developers can see this.

--

--

Pav Sidhu

👋🏼 I'm a developer, designer and Computer Science student.