What We’re Building

We’ll be building a sign up form that has the following fields

Email (required)

Username (optional)

Password (required)

Agree to terms (required)

Defining the Form Model

The first thing we need to do is define a model for our form — this is what will be passed to the form component and used to render the fields.

When defining the model we need to specify at minimum the field and the type of value that it accepts.

We’re just using a few of the different types but there are more available.

Let’s go ahead and actually render this form to see what we’ve got. First we need to get the Form component (line 6) then we need to render the form and pass our model to it as the type (line 19).

Capturing Form Data

Good start! Now let’s actually try to capture that data. We’ll just use the basic Button component (which comes from react-native) to do this and add a handleSubmit function to the component.

Now to actually access and work with our form we need to add a reference to it and with that we should be able to call getValue() from handleSubmit .

However when you press “Sign Up” all the fields go red — automatic validation!

That’s coming from when we defined our model earlier. However, the username should be an optional field. Let’s fix that.

Customizing the Form

To do that we’ll use t.maybe to tell tcomb it’s an optional field.

Boom. That easy.

I also want to change the label for the “Terms” field. I want it to say “Agree to Terms” — we can do this via options passed to the Form .

This part is a bit verbose but it makes sense the way it’s set up. We create an object, add a key named “fields” (since we’re modifying the fields), add a key to this object that aligns with the key in our model (“terms”), and then inside that object we set the new label.

Code is easier to understand.

Then pass those options to the Form component

Let’s do the same thing to add some error messages.

#HonestErrorMessages

Modifying the Form Design

The final thing I want to do is modify the design of this form slightly. You can do quite a few things but I’m just going to be changing the label color on this one form.

The first thing I’m going to do is create a new formStyles object and copy over all of the default styles so I don’t have to start from scratch.

Here’s the full default stylesheet.

Then I’ll customize it with my A+ design skillz.

Simple & beautiful design modifications. Just about everything in the default form is customizable.

As you can see tcomb-form-native makes building forms quick and easy but also gives you the flexibility you need to create forms the give users the necessary info and fit with the rest of your app (unless I’m designing of course).

You can get the final code on Snack.