0

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

2
  • 1
    can you try property !== "address2" ? Commented Feb 26, 2021 at 6:36
  • you were right. you can post this as answer. I will accept it. thanks. Commented Feb 26, 2021 at 6:46

2 Answers 2

1

can you try if (property !== "address2") or if (!(property === "address2"))

Sign up to request clarification or add additional context in comments.

Comments

1

I would change

if (!property === "address2") 

to

if (property !== "address2") 

as you are equating the property to address2 and address2 is certainly not boolean neither is property if my assumptions are correct.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.