skip to Main Content

Currently i am using Angular JS and using form validation as below:

               <div class="form-group" ng-class="{ 'has-error' : validating && form.name.$invalid }">
                    <label for="name" class="col-md-3 control-label">Name</label>
                    <div class="col-md-9">
                        <input type="text" id="name" name="description" ng-model="name" class="form-control" required />
                    </div>
                </div>

So basically if Name is not populated the form is invalid.

Is there an equivalent way in ReactJS ?

3

Answers


  1. The HTML attribute required will work in react jsx component also. If you require to add more validations like length of name or check any special chars, you can store the input field value in a state using useState hook and check manually while submitting.

    import React, { useState } from 'react';
    
    function MyForm() {
      const [formData, setFormData] = useState({
        name: '',
        // ...other form fields
      });
    
      const [errors, setErrors] = useState({
        name: '',
        // ...other form fields' errors
      });
    
      const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData((prevData) => ({
          ...prevData,
          [name]: value,
        }));
      };
    
      const validateForm = () => {
        let isValid = true;
    
        // You can add your own validation here
        if (formData.name.trim() === '') {
          setErrors((prevErrors) => ({
            ...prevErrors,
            name: 'Name is required.',
          }));
          isValid = false;
        } else {
          setErrors((prevErrors) => ({
            ...prevErrors,
            name: '',
          }));
        }
        return isValid;
      };
    
      const handleSubmit = (e) => {
        e.preventDefault();
        // validate before submitting
        validateForm()
      };
    
      return (
        <form onSubmit={handleSubmit}>
          <div>
            <label>Name:</label>
            <input
              type="text"
              value={formData.name}
              onChange={handleChange}
            />
            {errors.name && <span className="error">{errors.name}</span>}
          </div>
          <button type="submit">Submit</button>
        </form>
      );
    }
    
    export default MyForm;
    
    Login or Signup to reply.
  2. Of course, you can do that. The easiest way is to use third party library such as react-hook-form.

    For example:

    import React from "react";
    import { useForm } from "react-hook-form";
    
    export default function App() {
      const { register, handleSubmit, formState } = useForm();
    
      const onSubmit = (data) => {
        console.log(data);
      };
    
      return (
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="form-group">
            <label htmlFor="name" className="col-md-3 control-label">
              Name
            </label>
            <div className="col-md-9">
              <input
                type="text"
                id="name"
                name="name"
                {...register("name", { required: true })}
                className="form-control"
              />
              {formState.isDirty && formState.errors.name && (
                <span className="has-error">Name is required</span>
              )}
            </div>
          </div>
          <input type="submit" />
        </form>
      );
    }
    

    This way, you can implement validation in the form.

    To learn more, please see React Hook Form Documentation.

    Login or Signup to reply.
  3. For simple form, you can handle it manually using useState, demo

    But for complicated form you can use 3rd party like react-hook-form to handle form. It has some features like watch the field change, schema validate…:

    <form onSubmit={handleSubmit(onSubmit)}>
      <div className={`form-group ${errors.name ? "has-error" : ""}`}>
        <label htmlFor="name" className="col-md-3 control-label">
          Name
        </label>
        <div className="col-md-9">
          <input
            type="text"
            id="name"
            name="name"
            className="form-control"
            {...register("name", { required: true })}
          />
        </div>
        {errors.name && <p className="error">Name is required</p>}
      </div>
      <input type="submit" />
    </form>
    

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search