React Js Form Validation

Vikas Kohli
4 min readDec 27, 2018

--

In this module, I am doing form validation in Reactjson touch and submit events:-

app.js / index.js file

import RegisterForm from './components/register-form';class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="center">
<RegisterForm>
</ RegisterForm>
</div>)
}
};ReactDOM.render(
<App />,
document.getElementById('app')
);

register-form.js is a file in which I have added registration form and I kept this file in the components folder. That’s why I added as import RegisterFormfrom ‘./components/register-form’` in the app.js/index.js file

class RegisterForm extends React.Component {
constructor() {
super();
this.state = {
fields: {},
errors: {},
touched: {},
formSubmitted: false
}
// this.handleChange = this.handleChange.bind(this);
this.submituserRegistrationForm = this.submituserRegistrationForm.bind(this);
};handleChange(e) {
let fields = this.state.fields;
console.log("dfddf",e.target.name,e.target.value);
fields[e.target.name] = e.target.value;
this.setState({
fields
});
}

handleTouch(e){
let {touched} = this.state;
if(e.target.name && touched[e.target.name] != true){
touched[e.target.name] = true;
this.setState({
touched
});
}
}

submituserRegistrationForm(e) {
e.preventDefault();
this.setState({
formSubmitted: true
});
if (this.validateForm()) {
let fields = {};
fields["username"] = "";
fields["emailid"] = "";
fields["mobileno"] = "";
fields["password"] = "";
this.setState({fields:fields});
this.setState({
formSubmitted: false
});
alert("Form submitted");
}
}validateForm() {let fields = this.state.fields;
let errors = {};
let formIsValid = true;
console.log(fields, "fields");
if (!fields["username"]) {
formIsValid = false;
errors["username"] = "*Please enter your username.";
}
if (typeof fields["username"] !== "undefined") {
if (!fields["username"].match(/^[a-zA-Z ]*$/)) {
formIsValid = false;
errors["username"] = "*Please enter alphabet characters only.";
}
}
if (!fields["emailid"]) {
formIsValid = false;
errors["emailid"] = "*Please enter your email-ID.";
}
if (typeof fields["emailid"] !== "undefined") {
//regular expression for email validation
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
if (!pattern.test(fields["emailid"])) {
formIsValid = false;
errors["emailid"] = "*Please enter valid email-ID.";
}
}
if (!fields["mobileno"]) {
formIsValid = false;
errors["mobileno"] = "*Please enter your mobile no.";
}
if (typeof fields["mobileno"] !== "undefined") {
if (!fields["mobileno"].match(/^[0-9]{10}$/)) {
formIsValid = false;
errors["mobileno"] = "*Please enter valid mobile no.";
}
}
if (!fields["password"]) {
formIsValid = false;
errors["password"] = "*Please enter your password.";
}
if (typeof fields["password"] !== "undefined") {
if (!fields["password"].match(/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%&]).*$/)) {
formIsValid = false;
errors["password"] = "*Please enter secure and strong password.";
}
}
this.setState({
errors: errors
});
return formIsValid;
}render() {
return (
<div id="main-registration-container">
<div id="register">
<h3>Registration page</h3>`
<form method="post" name="userRegistrationForm" onSubmit= {this.submituserRegistrationForm} >
<label>Name</label>
<input type="text" name="username" value={this.state.fields.username}
onChange={ (e) => {this.handleChange(e);this.validateForm();} }
onBlur = {(e) => {this.handleTouch(e);this.validateForm();} } />
{
this.state.formSubmitted || this.state.touched.username
?
<div className="errorMsg">{this.state.errors.username}</div>
:
''
}
<label>Email ID:</label>
<input type="text" name="emailid" value={this.state.fields.emailid}
onChange={ (e) => {this.handleChange(e);this.validateForm();} }
onBlur = {(e) => {this.handleTouch(e);this.validateForm();} } />
{
this.state.formSubmitted || this.state.touched.emailid
?
<div className="errorMsg">{this.state.errors.emailid}</div>
:
''
}

<label>Mobile No:</label>
<input type="text" name="mobileno" value={this.state.fields.mobileno}
onChange={ (e) => {this.handleChange(e);this.validateForm();} }
onBlur = {(e) => {this.handleTouch(e);this.validateForm();} } />
{
this.state.formSubmitted || this.state.touched.mobileno
?
<div className="errorMsg">{this.state.errors.mobileno}</div>
:
''
}
<label>Password</label>
<input type="password" name="password" value={this.state.fields.password}
onChange={ (e) => {this.handleChange(e);this.validateForm();} }
onBlur = {(e) => {this.handleTouch(e);this.validateForm();} } />
{
this.state.formSubmitted || this.state.touched.password
?

<div className="errorMsg">{this.state.errors.password}</div>
:
''
}
<input type="submit" className="button" value="Register"/>
</form>
</div>
</div>
);
}
}export default RegisterForm;

In the above code, for fetching whether the input event is touched or not, I am using the onBlur method and in the constructor, I declare a touched object. If the input field is touched, I am making that input’s touch event is true. If username input is touched and then we are leaving focus from that input field, then I make this.state.touched.username = true. Also I checked if its not true, then we are changing that value as it will increase the performance too

.scss file I am using for styling the registration form.

#register, #login {
width: 300px;
border: 1px solid #d6d7da;
padding: 0px 15px 15px 15px;
border-radius: 5px;
font-family: arial;
line-height: 16px;
color: #333333;
font-size: 14px;
background: #ffffff;
margin: 100px auto;
}
form label, form input {
display: block;
//margin-bottom: 10px;
width: 90%
}
form input {
padding: 10px;
border: solid 1px #BDC7D8;
}.button {
background-color: #00BFFF;
border-color: #3ac162;
font-weight: bold;
padding: 12px 15px;
color: #ffffff;
}
.errorMsg {
color: #cc0000;
margin-bottom: 12px;
}
.sucessMsg {
color: #6B8E23;
margin-bottom: 10px;
}

By doing this, we can achieve the form Validation in React js. Also in Angular, this type of form validation we’re doing but the difference is that Angular itself provided that events like

  1. Input fields have the following states:
  • $untouched The field has not been touched yet
  • $touched The field has been touched
  • $pristine The field has not been modified yet
  • $dirty The field has been modified
  • $invalid The field content is not valid
  • $valid The field content is valid

They are all properties of the input field and are either true or false.

2. Forms have the following states:

  • $pristine No fields have been modified yet
  • $dirty One or more have been modified
  • $invalid The form content is not valid
  • $valid The form content is valid
  • $submitted The form is submitted

Like the custom touched event I have created in Reactjs, ||ly we can also use other events by making custom functions for that. Like for dirty event. By default, we can make a dirty object and by default, we set false to all the fields. Under onChange event, we set true or false to that object fields

--

--

Vikas Kohli
Vikas Kohli

Written by Vikas Kohli

B.E Software Developer, Enthusiastic, Ego-surfing

No responses yet