HI WELCOME TO SIRIS

React Form Validations

Leave a Comment
Form validation is always a crucial task for any platform like for web application and mobile application, motive behind form validations is to get the expected data from the user based on the product requirement, and before uploading the user data into the server, it is necessary to check the format either it is valid or not. Form validation will be normally categories into two main categories.
  • Client side validation
  • Server-side validation
In client-side validation, the data will be validated before sending it to the server, where server-side works opposite of client-side in which data sent to server side as request and after validating data, the server sends acknowledgment as a response.
In this article, we are going to learn about basic form validation using custom validation strategies.

Required Validation

Sometimes we have the form in which all fields should be required to be filled by the end user; in this case, we can implement required validation to make end-user enter all the values of form controls before submitting the form. Many browsers support required filed validators, but it may also possible that it won’t work on some browser and can work on the specific browser, so for that, we cannot use inbuilt validator because it is browser specific required validators.

Example

If we use “required” along with input form control so it works as expected like this. Create a new file called Demo.html and paste following code.
Demo.html
  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <form name="myForm" method="post">
  5. First Name :
  6. <input required type="text" name="firstname">
  7. <input type="submit" value="Submit">
  8. </form>
  9. </body>
  10. </html>
Now run above file in the browser, I’m using Google Chrome and see the output.
As can see into a demo.html file, that I have not implemented any logic which handles required field validation, thus it's working as expected, it's working because JavaScript supports validation like this and keep in mind that not all browser supports required validator.

Create React App

To getting started with form validation using React application, our first required step is to create a new react app. Execute below command to install create-react-app which is a tool which provides us with a ready and simple project with the setup to get us started easily with react.
Npm install create-react-app
When we did with the installation part, now it’s time to create new react app using below npm command.
Create-react-app react-forms-validations

Implement Required Field Validation Using React

In this article, we are going to implement simple and custom validations with different types of the form element, to get started we need to create a new folder named Forms inside the src directory.And inside Forms directory, create a new file named SimpleForm.js and paste following source code.
/Src/Forms/SimpleForm.js
  1. import React, { Component } from 'react';
  2.  
  3. class SimpleForm extends Component {
  4.  
  5. constructor() {
  6. super();
  7. this.state = {
  8. formFields: {
  9. firstName: '',
  10. lastName: '',
  11. email: '',
  12. password: ''
  13. },
  14. errors: {}
  15. }
  16. this.handleChange = this.handleChange.bind(this);
  17. this.handleSubmit = this.handleSubmit.bind(this);
  18. };
  19.  
  20. // When any field value changed
  21. handleChange(event) {
  22. let formFields = this.state.formFields;
  23. formFields[event.target.name] = event.target.value;
  24. this.setState({
  25. formFields
  26. });
  27. }
  28.  
  29. // To validate all form fields
  30. validate() {
  31. let formFields = this.state.formFields;
  32. let errors = {};
  33. let IsValid = true;
  34.  
  35. if (!formFields["firstName"]) {
  36. IsValid = false;
  37. errors["firstName"] = "Enter Your First Name";
  38. }
  39.  
  40. if (!formFields["lastName"]) {
  41. IsValid = false;
  42. errors["lastName"] = "Enter Your Last Name";
  43. }
  44.  
  45. if (!formFields["email"]) {
  46. IsValid = false;
  47. errors["email"] = "Enter Your Email";
  48. }
  49.  
  50. if (!formFields["password"]) {
  51. IsValid = false;
  52. errors["password"] = "Enter The Password";
  53. }
  54.  
  55. this.setState({
  56. errors: errors
  57. });
  58. return IsValid;
  59. }
  60.  
  61. // When user submits the form after validation
  62. handleSubmit(event) {
  63. event.preventDefault();
  64. if (this.validate()) {
  65. let formFields = {};
  66. formFields["firstName"] = "";
  67. formFields["lastName"] = "";
  68. formFields["email"] = "";
  69. formFields["password"] = "";
  70. this.setState({ formFields: formFields });
  71. }
  72. }
  73.  
  74. render() {
  75. return (
  76. <div className="container" style={{ width: '315px' }}>
  77. <h3>Employee Registration With Required Validation</h3>
  78. <form onSubmit={this.handleSubmit} >
  79. <div className="form-group">
  80. <label>First Name</label>
  81. <input className="form-control"
  82. type="text"
  83. name="firstName"
  84. value={this.state.formFields.firstName}
  85. onChange={this.handleChange} />
  86. {this.state.errors.firstName &&
  87. <div className="alert alert-danger">
  88. {this.state.errors.firstName}
  89. </div>
  90. }
  91. </div>
  92. <div className="form-group">
  93. <label>Last Name</label>
  94. <input className="form-control"
  95. type="text"
  96. name="lastName"
  97. value={this.state.formFields.lastName}
  98. onChange={this.handleChange} />
  99. {this.state.errors.lastName &&
  100. <div className="alert alert-danger">
  101. {this.state.errors.lastName}
  102. </div>
  103. }
  104. </div>
  105. <div className="form-group">
  106. <label>Email</label>
  107. <input className="form-control"
  108. type="text"
  109. name="email"
  110. value={this.state.formFields.email}
  111. onChange={this.handleChange} />
  112. {this.state.errors.email &&
  113. <div className="alert alert-danger">
  114. {this.state.errors.email}
  115. </div>
  116. }
  117. </div>
  118. <div className="form-group">
  119. <label>Password</label>
  120. <input className="form-control"
  121. type="text"
  122. name="password"
  123. value={this.state.formFields.password}
  124. onChange={this.handleChange} />
  125. {this.state.errors.password &&
  126. <div className="alert alert-danger">
  127. {this.state.errors.password}
  128. </div>
  129. }
  130. </div>
  131. <input type="submit" className="btn btn-primary" value="Submit" />
  132. </form>
  133. </div >
  134. );
  135. }
  136. }
  137.  
  138. export default SimpleForm;
Let me explain all the things which I have implemented in this file.
  • Declared states with form fields to store the form element’s value
  • Created two different methods which are used to handle the form element values and another one is used to validate the user inputs before submitting the form.
  • An important method is handleSubmit, which is used to submit the form data after validating each of the form fields.
  • Inside render methods, I have created a form with different form fields with the error part, where we are going to display a different error message.
This is kind of re-usable component, In order to execute this for we need to add it into the main component App.js which is the main component for our react application.
App.js
  1. import React, { Component } from 'react';
  2. import './App.css';
  3. import SimpleForm from './Forms/SimpleForm';
  4.  
  5. class App extends Component {
  6. render() {
  7. return (
  8. <div className="App demoForm">
  9. <h1>React Form Validations</h1><hr style={{ borderTop: '3px solid purple' }} />
  10. <SimpleForm />
  11. </div>
  12. );
  13. }
  14. }
  15.  
  16. export default App;
In this file, I have imported our SimpleForm.js file, where we have created our form and let’s see how it works.

Output

Run react application using npm command npm start and the output look like this when we directly submit our code without providing any values.
As you can see into above image that when we directly click on the submit button without providing form values then it displays the all error message like this.Now we are going to provide all the form fields values and see the output.
When we submit the form with all required fields, then we are ready to send the forms data to the server, this is how you can implement using conditions.

Implement Different custom validations

Previously, we have seen the simply required field validation using custom code, now let’s add more flavors but with the same form fields using different validation criteria.Create a new file inside Forms folder named RegistrationForm.js and paste the following source code.
/Src/Forms/RegistrationForm.js
  1. import React, { Component } from 'react';
  2.  
  3. class RegistrationForm extends Component {
  4.  
  5. constructor() {
  6. super();
  7. this.state = {
  8. formFields: {
  9. firstName: '',
  10. lastName: '',
  11. email: '',
  12. password: ''
  13. },
  14. errors: {}
  15. }
  16. // To bind different events
  17. this.handleChange = this.handleChange.bind(this);
  18. this.handleSubmit = this.handleSubmit.bind(this);
  19. };
  20.  
  21. // When any field value changed
  22. handleChange(event) {
  23. let formFields = this.state.formFields;
  24. formFields[event.target.name] = event.target.value;
  25. this.setState({
  26. formFields
  27. });
  28. }
  29.  
  30. // To validate all form fields
  31. validate() {
  32. let formFields = this.state.formFields;
  33. let errors = {};
  34. let IsValid = true;
  35.  
  36. if (!formFields["firstName"]) {
  37. IsValid = false;
  38. errors["firstName"] = "Enter Your First Name";
  39. }
  40.  
  41. // To allow only alphabets value
  42. if (typeof formFields["firstName"] !== "undefined") {
  43. if (!formFields["firstName"].match(/^[a-zA-Z ]*$/)) {
  44. IsValid = false;
  45. errors["firstName"] = "Only Alphabet Characters Are Allowed";
  46. }
  47. }
  48.  
  49. if (!formFields["lastName"]) {
  50. IsValid = false;
  51. errors["lastName"] = "Enter Your Last Name";
  52. }
  53.  
  54. // To allow only alphabets value
  55. if (typeof formFields["lastName"] !== "undefined") {
  56. if (!formFields["lastName"].match(/^[a-zA-Z ]*$/)) {
  57. IsValid = false;
  58. errors["lastName"] = "Only Alphabet Characters Are Allowed";
  59. }
  60. }
  61.  
  62. if (!formFields["email"]) {
  63. IsValid = false;
  64. errors["email"] = "Enter Your Email";
  65. }
  66.  
  67. // To allow valid email format
  68. if (typeof formFields["email"] !== "undefined") {
  69. var pattern = new RegExp(/^[a-z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+)?$/);
  70. if (!pattern.test(formFields["email"])) {
  71. IsValid = false;
  72. errors["email"] = "Invalid Email";
  73. }
  74. }
  75.  
  76. if (!formFields["password"]) {
  77. IsValid = false;
  78. errors["password"] = "Enter The Password";
  79. }
  80.  
  81. // Should have valid password format
  82. if (typeof formFields["password"] !== "undefined") {
  83. if (!formFields["password"].match("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})")) {
  84. IsValid = false;
  85. errors["password"] = "Enter Valid Password";
  86. }
  87. }
  88.  
  89. this.setState({
  90. errors: errors
  91. });
  92. return IsValid;
  93. }
  94.  
  95. // When user submits the form after validation
  96. handleSubmit(event) {
  97. event.preventDefault();
  98. if (this.validate()) {
  99. let formFields = {};
  100. formFields["firstName"] = "";
  101. formFields["lastName"] = "";
  102. formFields["email"] = "";
  103. formFields["password"] = "";
  104. this.setState({ formFields: formFields });
  105. }
  106. }
  107.  
  108. render() {
  109. return (
  110. <div className="container" style={{ width: '315px' }}>
  111. <h3>Employee Registration With Different Validations</h3>
  112. <form onSubmit={this.handleSubmit} >
  113. <div className="form-group">
  114. <label>First Name</label>
  115. <input className="form-control"
  116. type="text"
  117. name="firstName"
  118. value={this.state.formFields.firstName}
  119. onChange={this.handleChange} />
  120. {this.state.errors.firstName &&
  121. <div className="alert alert-danger">
  122. {this.state.errors.firstName}
  123. </div>
  124. }
  125. </div>
  126. <div className="form-group">
  127. <label>Last Name</label>
  128. <input className="form-control"
  129. type="text"
  130. name="lastName"
  131. value={this.state.formFields.lastName}
  132. onChange={this.handleChange} />
  133. {this.state.errors.lastName &&
  134. <div className="alert alert-danger">
  135. {this.state.errors.lastName}
  136. </div>
  137. }
  138. </div>
  139. <div className="form-group">
  140. <label>Email</label>
  141. <input className="form-control"
  142. type="text"
  143. name="email"
  144. value={this.state.formFields.email}
  145. onChange={this.handleChange} />
  146. {this.state.errors.email &&
  147. <div className="alert alert-danger">
  148. {this.state.errors.email}
  149. </div>
  150. }
  151. </div>
  152. <div className="form-group">
  153. <label>Password</label>
  154. <input className="form-control"
  155. type="text"
  156. name="password"
  157. value={this.state.formFields.password}
  158. onChange={this.handleChange} />
  159. {this.state.errors.password &&
  160. <div className="alert alert-danger">
  161. {this.state.errors.password}
  162. </div>
  163. }
  164. </div>
  165. <input type="submit" className="btn btn-primary" value="Submit" />
  166. </form>
  167. </div >
  168. );
  169. }
  170. }
  171.  
  172. export default RegistrationForm;
In this form, we are going to validate different elements with different conditions.
  1. All fields are required by default
  2. The first name can not contain the characters other than alphabets
  3. The last name cannot contain the characters other than alphabets
  4. The email address should be a valid format like :
    • The first character should be lower case
    • Must contains @ symbol
    • Must have a dot(.) after the @ symbol
  5. The password should match some conditions like :
    • At least 1 Uppercase latter
    • At least 1 Lowercase latter
    • At least one special character like @#$&
    • At least 8 characters long password
So when user fulfills all the above primary requirements than the form can be submitted otherwise it won’t possible to process further without solving all remaining conditions.To run above example, we need to import it into App.js component like this.
App.js
  1. import React, { Component } from 'react';
  2. import './App.css';
  3. import RegistrationForm from './Forms/RegistrationForm';
  4.  
  5. class App extends Component {
  6. render() {
  7. return (
  8. <div className="App demoForm">
  9. <h1>React Form Validations</h1><hr style={{ borderTop: '3px solid purple' }} />
  10. <RegistrationForm />
  11. </div>
  12. );
  13. }
  14. }
  15.  
  16. export default App;

Output

To demonstrate that all validations are working properly, I am going to provide invalid values to form fields like this.
In this form, I have provided invalid values against the policy, other than email address where I have provided the valid format.When I submit after providing all valid data than I will be able to submit the form successfully like this.
This is how we have implemented form validations with different conditions with required validation, but still, you can expand it as per your different requirements.
Summary
In this article, we have learned how to implement simple and custom validations using different conditions, thus we can make use of other third-party libraries to achieve the same result, if you want to try custom validation than download source code attached to this article and implement different validation like file validation, length validation, strangeness validation etc, Thanks for reading.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.