Software Development

React Native vs Native: Which One To Choose For Your Mobile App

admin
14 April 2024
React Native vs Native: Which One To Choose For Your Mobile App

Summary : This in-depth course will examine how to use React hooks and the third-party React Hook Form module to build form validations in React. We’ll streamline the process of implementing form validation in React and highlight the advantages of user input.

Online marketplace demand is rising in today’s digital age. To accommodate this need, a lot of businesses are moving their activities online. As such, forms are now included on the majority of websites and applications. For error-free data entry and a seamless user experience, form validation must be implemented.

This validation procedure confirms that user input satisfies the necessary requirements. React form validation is now much more efficient thanks to the incorporation of React hooks. The goal of this lesson is to help you use React hooks to create user-friendly forms and error-free inputs. For validation, we’ll use the React Hook Form module.

Understanding Form Validation in React

Form validation is the process of confirming that user inputs satisfy predetermined standards. Form validation can be used to stop users from entering inaccurate or missing data. This video teaches you how to use React hooks to build error-free inputs that guarantee the creation of a form that is easy to use and has the necessary validations.

How to Build Form Validation in React?

We will create a form that lets users enter data in this lesson. The steps to create form validation in React are as follows. To get our project going, we will first build up our components using the Create React App. Using this program, we may launch a new project by running the following commands:

Create React App

Setting up the form

Form.js and style.css are the two prerequisites for creating a form. Form.js will manage the functionality and validity of the form, while Style.css will specify how our webpage will look.

The css to be immediately integrated into your Form can be found below.For CSS details, use the js component.

Form.js

				
					import React from "react";
 import "./styles.css";


 function Form() {
   return (
     <div className="container">
       <h1>Contact Form</h1>
       <form>
         <div className="form-group">
           <label htmlFor="name">Name:</label>
           <input type="text" id="name" name="name" />
         </div>
         <div className="form-group">
           <label htmlFor="email">Email:</label>
           <input type="email" id="email" name="email" />
         </div>
         <button type="submit">Submit</button>
       </form>
     </div>
   );
 }



 export default Form;
				
			

Styles.css

				
					.container {
 max-width: 400px;
 margin: 0 auto;
 padding: 20px;
 border: 1px solid #ccc;
 border-radius: 5px;
}
.form-group {
 margin-bottom: 15px;
}
label {
 display: block;
 margin-bottom: 5px;
}
input[type="text"],
input[type="email"],
textarea {
 width: 100%;
 padding: 10px;
 border: 1px solid #ccc;
 border-radius: 5px;
}
button {
 padding: 10px 20px;
 background-color: #007bff;
 color: #fff;
 border: none;
 border-radius: 5px;
 cursor: pointer;
}
button:hover {
 background-color: #0056b3;
}
.error {
 display: block;
 color: #dc3545;
 font-size: 14px;
 margin-top: 5px;
}
.error::before {
 content: "\26A0"; /* Warning symbol */
 margin-right: 5px;
}
				
			

Implementing Form Validation Using React Hooks

With our Form now styled appropriately, we can integrate validation into the form. There are different styles to implement form validation using React Hooks. Let us simplify the process to implement form validation in React with the following steps:

🟠 State Management

				
					const [formData, setFormData] = useState({
   name: "",
   email: "",
 });
 const [errors, setErrors] = useState({});
				
			

✔ FormData: Two keys, “name” and “email,” are present in the FormData state. Initially, the objects had blank “name” and “email” fields. These values are kept in the formData state within the appropriate keys as the user enters data.

✔ Errors: In charge of managing validation errors; initially assigned an empty object.

Create contact form

				
					const handleChange = (e) => {
   const { name, value } = e.target;
   setFormData((prevState) => ({
     ...prevState,
     [name]: value,
   }));
 };


 const handleSubmit = (e) => {

   e.preventDefault();
   const validationErrors = validateForm(formData);
   if (Object.keys(validationErrors).length === 0) {
     // Form submission logic here
     console.log(formData);
   } else {
     setErrors(validationErrors);
   }
 };
				
			

🟠 Event Handlers

✏ handleChange: Handles input field changes and modifies the email and name fields as necessary.

✏ handleSubmit: Starts the validation and submission of forms.

🟠 Form Validation

✏ validateForm: Verifies the form by determining whether the “name” and “email” fields are both empty or include valid email formats. Any validation errors discovered are returned in an object.

✏ isValidEmail: Makes use of a regular expression to carry out basic email validation.

				
					const validateForm = (data) => {
   let errors = {};
   if (!data.name) {
     errors.name = "Name is required";
   }
   if (!data.email.trim()) {
     errors.email = "Email is required";
   } else if (!isValidEmail(data.email)) {
     errors.email = "Invalid email format";
   }
   return errors;
 };


 const isValidEmail = (email) => {
   // Basic email validation
   return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
 };
				
			

In the event that the user tries to submit the form without completing the necessary fields, this validation function will provide error messages like “Email required” and “Name required.”

Contact Form

Below is the complete code provided regarding form validation using React hooks.

				
					import React, { useState } from "react";
 import "./styles.css";


 function Form() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
  });
 
  const [errors, setErrors] = useState({});
 
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };
 
  const handleSubmit = (e) => {
    e.preventDefault();
    const validationErrors = validateForm(formData);
    if (Object.keys(validationErrors).length === 0) {
      // Form submission logic here
      console.log(formData);
    } else {
      setErrors(validationErrors);
    }
  };


  const validateForm = (data) => {
    let errors = {};
    if (!data.name) {
      errors.name = "Name is required";
    }
    if (!data.email.trim()) {
      errors.email = "Email is required";
    } else if (!isValidEmail(data.email)) {
      errors.email = "Invalid email format";
    }
    return errors;
  };


  const isValidEmail = (email) => {
    // Basic email validation
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  };


  return (
    <div className="container">
      <h1>Contact Form</h1>
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="name">Name:</label>
          <input
            type="text"
            id="name"
            name="name"
            value={formData.name}
            onChange={handleChange}
          />
          {errors.name && <span className="error">{errors.name}</span>}
        </div>
        <div className="form-group">
          <label htmlFor="email">Email:</label>
          <input
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
          />
          {errors.email && <span className="error">{errors.email}</span>}
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
 }



 export default Form;
				
			

Implementing Form Validation using React Hook Form Library

Let’s take a closer look at how to use the React Hook Form module to add form validation. Everything you need to know about installing, using, and applying validation to the form is covered in our explanation of the React Hook Form library’s form validation features.

How to Install React Hook Form

				
					npm install react-hook-form
				
			

You may get a detailed description of this library in the NPM packages documentation. For further specifics and information, click visit this page.

Usage of React Hook Form

1. Import and destructure: Destructure the necessary properties after importing the useForm hook.

				
					 import { useForm } from 'react-hook-form';


 const { register, handleSubmit, formState: { errors } } = useForm();
				
			

2. Register form fields: To register every form field, use the register function. Give a name for the key and any optional validation rules.

				
					<label htmlFor="name">Name:</label>
 <input
     type="text"
     id="name"
     {...register('name', { required: true })}
 />
				
			
				
					 
<label htmlFor="email">Email:</label>
 <input
     type="email"
     id="email"
     {...register('email', { required: true, pattern: /^\S+@\S+$/i })}
 />
				
			

3. Create onSubmit handler: Create a function that will handle submitting forms and accept the form data as an argument:

				
					 const onSubmit = (data) => {  
  // Handle form submission logic here
    console.log('FormData', data);
  };
				
			

4. Wrap form in handleSubmit: Use handleSubmit to encapsulate your form component and pass the onSubmit function:

				
					<form onSubmit={handleSubmit(onSubmit)}>
				
			

For your reference, the entire code is attached here, with the two fields that have been registered thus far.

				
					import React from "react";
 import { useForm } from 'react-hook-form';
 import './styles.css';


 function Form() {
  const { register, handleSubmit, formState: { errors } } = useForm();


 const onSubmit = (data) => {  
  // Handle form submission logic here
    console.log('FormData', data);
  };
  return (
    <div className="container">
      <h1>Contact Form</h1>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="form-group">
          <label htmlFor="name">Name:</label>
          <input
            type="text"
            id="name"
            {...register('name')}
          />
        </div>
        <div className="form-group">
          <label htmlFor="email">Email:</label>
          <input
            type="email"
            id="email"
            {...register('email')}
          />
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
 }



 export default Form;
				
			

Adding Validations to Form

This completes the process of validating our form. First, let’s address the name of the field. We’ll make advantage of the necessary asset.

1. Required field: To designate a field as required, use the required property in the register. An error message that appears beneath the input tag will be triggered if the user submits the form with the name field empty:

				
					<label htmlFor="name">Name:</label>
 <input
    type="text"
    id="name"
    {...register('name', { required: true })}
 />

				
			
				
					 {errors.name && Name is required}
				
			

Here is an error message that you will get after following the above-mentioned code.

Error Message

2. Email validation: To validate the email format, use the pattern property in conjunction with a regular expression:

				
					<label htmlFor="email">Email:</label>
 <input
     type="email"
     id="email"
     {...register('email', { required: true, pattern:/^\S+@\S+\.\S+$/})}
 />

				
			

3. Displaying error messages: Render error messages conditionally using the errors object from formState:

				
					 {errors.email && errors.email.type === 'required' && (
      Email is required
  )}
  {errors.email && errors.email.type === 'pattern' && (
      Invalid email format
   )}
				
			

Here’s the full code for form validation using the React Hook form, which you can understand:

				
					import React from 'react';
 import { useForm } from 'react-hook-form';
 import './styles.css';


 function Form() {
  const { register, handleSubmit, formState: { errors } } = useForm();


  const onSubmit = (data) => {
    // Handle form submission logic here
    console.log('FormData', data);
  };


  return (
    <div className="container">
      <h1>Contact Form</h1>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="form-group">
          <label htmlFor="name">Name:</label>
          <input
            type="text"
            id="name"
            {...register('name', { required: true })}
          />
          {errors.name && <span className="error">Name is required</span>}
        </div>
        <div className="form-group">
            <label htmlFor="email">Email:</label>
            <input
              type="email"
              id="email"
               {...register('email', { required: true, pattern:/^\S+@\S+\.\S+$/})}
            />
          {errors.email && errors.email.type === 'required' && (
            <span className="error">Email is required</span>
          )}
          {errors.email && errors.email.type === 'pattern' && (
            <span className="error">Invalid email format</span>
          )}
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
 }


 export default Form;
				
			

Displaying error messages

Conclusion

We have covered every aspect of form validation in React in this extensive tutorial, making use of the React Hook Form library in addition to React hooks. recognizing the value of form validation in designing user-friendly interfaces and use React to create a simple form structure.

Form library and show how to use React Hooks for installation, form field registration, submission handling, error display, and form validation. Therefore, incorporating strong form validation methods into your React apps improves data integrity and user experience. You can get support or knowledge regarding form validation by getting in touch with a React JS development business.

 

Table of Contents

Recent Comments
    December 2024
    M T W T F S S
     1
    2345678
    9101112131415
    16171819202122
    23242526272829
    3031  
    Tags:
    androidiOSmobilemobile app development
    3 likes
    Leave a Comment
    Share:
    Social