Recently I started exploring React. Soon I reached to create and validate forms. It was OK till I created form components. But when it came to form validation, I started scratching my head. I searched on the web endlessly. What I found was third party React components like formsy-react and others.
My question is: 1. Do we have a default way of applying all types of form validations in React? 2. Or we have to depend on third party components? 3. Or write our own logic around validation (I have always hated form validations, at least in 2016 I dont want to do validations on my own for God's sake!).
Then I took a look at Angular 2 form validation! It was surprisingly well supported and easy. It is also supported in Angular 1. From all opinionated debates on the web I was under impression that React is superior to Angular. But in this scenario, it seems Angular has a great lead.
Am I missing anything?
Hi! I encourage you to try React Advanced Form.
This is a new form library which solves a lot of issues with the modern form solutions. It proves than you can create advanced forms without obscure HoC configurations, tons of boilerplate, and even keeping your form component stateless. There are lot of other features shipped out of the box as well.
For your validation case it would offer you to declare a simple validation schema:
import isEmail from 'validator/lib/isEmail';
export default {
type: {
/* Use anything as a resolver function */
email: ({ value }) => isEmail(value),
password: {
/* Have multiple validation rules on the same selector with ease */
capitalLetter: ({ value }) => /[A-Z]/.test(value)
oneNumber: ({ value }) => /[0-9]/.test(value)
}
},
name: {
confirmPassword: ({ value, fields }) => {
/* Declare validation logic based on the state of other fields */
return (value === fields.userPassword.password);
}
}
};
It focuses on the validation as an independent pure schema which is handled by the form automatically. Stop mixing view with validation and start expecting the form to do more than just fields rendering.
See some guidelines on the validation.
You are not missing anything. You have made the discovery that any sensible person does that Angular is far superior to React.
I can understand your pain, I am facing the same issues and I believe that create a wrapper around required components like input and select is only the best bet. I am also doing a blog series where I'm planning to cover all this in detail and how I solve this issue at my work.
classandobjects.com/right_form_validation_in_react
Here is a nice solution for React with form and validations: npmjs.com/package/react-awesome-form-validator . Hope you like it!
I think client side validation is something which ideally should not be mixed with business logic in the code. This library (developed by me) has been made with idea of wrapping your fields to be validated and you should be done leaving all validation task to the library.
The idea is to be able to wrap any kind of component. It supports material-ui components as well. If your component is not supported out of box, the support can be added easily.
Angular is an MVW framework whereas React is just a view library. If you need a proper architecture and other features like form validations etc, you can combine it with a framework like Angular (although many developers prefer flux architecture).
It is not fair to say that one is superior to the other. Both are different and handle things in different ways. According to me the best way to validate a form in React is to do it yourself.
I don't exactly know how Angular 2 does validations so can't speak for that. However, I will highlight couple of approaches you can take to do form validation in React, choice between the two approaches depends on your requirements for input fields.
First- You can assign an event handler on every input which will perform checks specific to that particular input field. Say you want to restrict an input field to only 140 characters. Here's a way to do it.
var ExampleForm = React.createClass({
// some stuff .....
checkStatusLimit: function(e) {
var status = e.target.value.trim();
if(status.length >= 140){
React.findDOMNode(this.refs.status).value = status.substr(0,140);
e.preventDefault();
//trigger error
//console.log('aah.. Status is not a story!')
}
// do stuff like updating state etc.
// this.setState({status: status});
},
submitForm: function(e) {
e.preventDefault();
// Dispatch an action or make an Ajax call to server using the state.
},
render: function() {
<form onSubmit={this.submitForm}>
<input type='text' ref='status' onChange={this.checkStatusLimit} />
<button type='submit' >Submit</button>
</form>
}
});
Second- In case you don't have the requirements of making customized checks you can use some library like validator which will save you from writing your regex or validations, you won't have to write a event handler for every input field but you still have to run validatons for all fields that you want to be validated before the form is submitted. Say you have two fields one where you have to check for proper email format and second for username which only allows numbers and strings.
var ExampleForm = React.createClass({
// some stuff .....
submitForm: function(e) {
e.preventDefault();
var email = React.findDOMNode(this.refs.email).value;
var username = React.findDOMNode(this.refs.username).value;
if(!validator.isEmail(email) || !validator.isAlphanumeric(username)){
//return and trigger Error.
}
// Dispatch an action or make an Ajax call to server with email and username.
},
render: function() {
<form onSubmit={this.submitForm}>
<input type='email' ref='email' />
<input type='text' ref='username' />
<button type='submit' >Submit</button>
</form>
}
});
You can also use a combination of these two to handle validations. Hope this helps.
Angular is a full MVC(Model View Controller) framework while react is just the V(view). It shouldn't be surprising that react does not have form validation(which is the work of the controller). But there are ways to do it. These should help
Kuldeep Saxena
I think you're looking for Angular 2 Reactive forms in React. Check out this library.
github.com/bietkul/react-reactive-form