jeudi 25 février 2021

i am using for loop in object in javascript, but one condition is creating issue

i have this validator function

 import validator from "validator";
 import isEmpty from "is-empty";

export default function validate(data) {
  const errors = {};

  for (const property in data) {
    console.log(property); //<---This is executed

    //exclude optional properties from validation
    if (!property == "address2") {
      console.log("i got called"); //<---but this is not
      //return error if any of the compulsory fields is empty
      if (isEmpty(data[property])) errors[property] = `${property} is required`;

      //phone number validation
      if (property === "number")
        if (validator.isMobilePhone(data[property], "any"))
          errors[property] = "please enter valid phone number";

      //return error if country is not Pakistan
      if (!property === "country")
        if (
          data[property].charAt[0].toUpperCase() + //convert first letter to uppercase
            data[property].slice(1).toLowerCase() !== //remaining to lowercase
          "Pakistan"
        )
          errors[
            property
          ] = `we care currently taking orders from only within Pakistan`;
    }
  }

  return {
    errors,
    isValid: isEmpty(errors),
  };
}

This is how i am calling the function in react from onClick event of button:

          <Button
          onClick={(event) => {
            //check validation
            const { errors, isValid } = validate(details);
            //if valid submit form else show errors
            isValid ? handleSubmit(event) : setErrors(errors);
          }}
          variant="contained"
          name="shipping"
        >
          Continue
        </Button>

This is the state object that is passed

const [details, setDetails] = useState({
      name: "",
      number: "",
      address1: "",
      address2: "",
      city: "",
      postalCode: "",
      country: "",
    });

all fields are empty but still empty errors object is being returned. Any help here is appreciated. thanks

Aucun commentaire:

Enregistrer un commentaire