Validate Field onBlur() using Props Bindings in mobx-react-form

NOTE – The new version of the package already implements this feature, consider this article only as an explanatory example.

In this article we are going to demonstrate how to implement fields onBlur Validation from scratch relying on the built-in APIs and Props Bindings functionalities and build our custom components.

Define a new onBlur() handler function

The function takes the field store in input and returns another function which accept a Proxy object in input.

We can compose the returned function with the built-in onBlur(e) and validate() methods of the field store passed to the main function.

Eventually we can change the validateOnChange Form Option to false and the validation will be executed only on Fields onBlur.

Now we can use the handler in 2 different ways:

Using Props Bindings Priority

As you can see in the following React Component, we are using the field.bind() method on the input tag (which can be a custom input component as well) in conjunction with the ES6 spread operator.

If we want to override the built-in field props, we have a good chance here passing some props to the bind() method. Then we pass the previously defined onBlur(field) handler (with the current field store as its input) to it.

This way the new behavior will work for all our input fields when using this component.

Read more about Using Default Bindings on the docs.

Using a Custom Bindings Template

With this method you have the chance to implement new bindings from scratch. For example you can create different templates and attach them to specific fields.

The bindings template is a function which takes 3 things in input: the $try() helper, the current field store, and the current props (passed to the field.bind() method).

Here we are defining a MyCustomInput template (but you can use the name you want) reimplementing the onBlur using our new handler which will take in input the current field store.

You can find all available Fields Properties and Event Handlers on the docs.

The $try() helper will check first if there is a custom onBlur as input for the .bind() method, if it doesn't exist will use the onBlur handler specifically defined for that binding template.

Then you can set a field bindings prop providing the template name when defining the fields props normally on Form Initialization or, eventually, dynamically using set():

field.set(‘bindings’, ‘MyCustomInput’);

Read more about Defining Custom Bindings on the docs.

The mobx-react-form package is now a solid choice if you need to handle also complex forms and validation.

Particular thanks go to who contributed with support, help and suggestions that made the package better day by day. Thank You!

If your are new to the mobx-react-form package, learn more on how to setup a simple login form: