Home > Mobile >  How can I add a form validation to this code?
How can I add a form validation to this code?

Time:01-09

I'm doing a multi step form, and I need to add a warning of empty fields. I'm posting my code, and one solution which I've google it below. I need some help to implement it on my code, I'm starting with react and jsx

import React from "react";

function PickAddons({ formData, setFormData }) {
 
  
  return (
    <div className="pick-addons-container">
      <div>Name</div>
      <input
        type="text"
        placeholder="Full Name"
        value={formData.fullName}
        onChange={(event) =>
          setFormData({ ...formData, fullName: event.target.value })
        }
      />
      <div>Email Adress</div>
      <input
        type="text"
        placeholder="Email Adress"
        value={formData.email}
        onChange={(event) =>
          setFormData({ ...formData, email: event.target.value })
        }
      />
      <div>Phone Number</div>
      <input
        type="text"
        placeholder="Confirm Password..."
        value={formData.confirmPassword}
        onChange={(event) =>
          setFormData({ ...formData, confirmPassword: event.target.value })
        }
      />
    </div>
  );
}

export default PickAddons;

I only have this but I can't figure out how to implement in my code.

 const [fullName, setfullName] = useState('')
  const [error, setError] = useState(false)

  const handleSubmit = (e) => {
    e.preventDefault();
    if (fullName.length == 0) {
      setError(true)
    }
    if (fullName) {
      console.log("First Name: ", fullName)
    }
  }

CodePudding user response:

onSubmit event handler to call the validateForm function when the form is submitted. If the validateForm function returns an error message, it is displayed to the user using an alert box. If the validateForm function returns nothing, the form data is submitted.

You can customize the validateForm function to check for any other conditions that you want to enforce in your form. For example, you could check that the email address is in a valid format, or that the password meets certain complexity requirements.

import React from "react";

function PickAddons({ formData, setFormData }) {
  const validateForm = () => {
    if (!formData.fullName) {
      return "Please enter a full name.";
    }
    if (!formData.email) {
      return "Please enter an email address.";
    }
    if (!formData.confirmPassword) {
      return "Please confirm your password.";
    }
  };

  return (
    <div className="pick-addons-container">
      <form onSubmit={(event) => {
        event.preventDefault();
        const errorMessage = validateForm();
        if (errorMessage) {
          alert(errorMessage);
        } else {
          // submit form data
        }
      }}>
        <div>Name</div>
        <input
          type="text"
          placeholder="Full Name"
          value={formData.fullName}
          onChange={(event) =>
            setFormData({ ...formData, fullName: event.target.value })
          }
        />
        <div>Email Adress</div>
        <input
          type="text"
          placeholder="Email Adress"
          value={formData.email}
          onChange={(event) =>
            setFormData({ ...formData, email: event.target.value })
          }
        />
        <div>Phone Number</div>
        <input
          type="text"
          placeholder="Confirm Password..."
          value={formData.confirmPassword}
          onChange={(event) =>
            setFormData({ ...formData, confirmPassword: event.target.value })
          }
        />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default PickAddons;

CodePudding user response:

There are two options.

One is to use validation module, another is to use your custom code.

https://www.npmjs.com/package/react-validation

In case of customization, it is better to use regular expression.

^[\w-.] @([\w-] .) [\w-]{2,4}$ 【email validation】 ^(?=.\d)(?=.[a-z])(?=.[A-Z])(?=.[a-zA-Z]).{8,}$ 【password validation】

CodePudding user response:

Have you used yup before? You can validate any data with it easily. Below is an example of yup

import * as yup from 'yup';

let schema = yup.object().shape({
  name: yup.string().required(),
  age: yup.number().required().positive().integer(),
  email: yup.string().email(),
  website: yup.string().url(),
  createdOn: yup.date().default(function () {
    return new Date();
  }),
});

// check validity
schema
  .isValid({
    name: 'jimmy',
    age: 24,
  })
  .then(function (valid) {
    valid; // => true
  });

Check out the yup: https://www.npmjs.com/package/yup

  • Related