Jin
Jin

Reputation: 1439

ERROR Cannot read property 'matches' of undefined

I have to check validation for form input, this is my code for that

//onSave is a button save 
const onSave = (event) => {
    const invalid = [];
    ["name", "description", "category"].forEach(key => {
      if (key.value.matches("/[0-9]+/)")) {
        invalid.push(key);
        alert("Not allow number here");
      }
    });
    if (values.name.trim() === "") {
      invalid.push("name");
      alert("Please not left blank form");
    } else {
      createProductRequest(values, imageAsFile);
    }
  };

And this is what set values for that field

const [values, setValues] = useState({
    image: "",
    name: "",
    price: 0,
    description: "",
    categoty: "",
  });

But after I try to enter in my form input is number I got this error

TypeError: Cannot read property 'matches' of undefined`
  <Form.Group controlId="name">
          <Form.Label>Name</Form.Label>
          <Form.Control
            type="text"
            placeholder="Enter product name"
            value={values.name}
            name="name"
            onChange={handleInputChange}
          >
          </Form.Control>
        </Form.Group>

The form for description and category is the same

Can anyone explain to me why please, I do not know where I am wrong?

Upvotes: 1

Views: 922

Answers (1)

akram-adel
akram-adel

Reputation: 1070

I looked at your previous question to get why you wrote the onSave function like this

In your react app you have a state like this

const [values, setValues] = useState({
    image: "",
    name: "",
    price: 0,
    description: "",
    categoty: "",
  });

To access these values in the onSave function your forEach loop should be changed to

["name", "description", "category"].forEach(key => {
  const value = (typeof values[key] === 'number')
    ? values[key].toString()
    : values[key];

  if (value.match(/[0-9]+/)) {
    invalid.push(key);
    alert("Not allow number here");
  }
});

And to stop pushing if there are any errors, your onSave function should be like:

const onSave = (event) => {
  const invalid = [];

  ["name", "description", "category"].forEach(key => {
    const value = (typeof values[key] === 'number')
      ? values[key].toString()
      : values[key];

    if (value.match(/[0-9]+/)) {
      invalid.push(key);
      alert("Not allow number here");
    }
  });

  if (values.name.trim() === "") {
    invalid.push("name");
    alert("Please not left blank form");
  }

  // Only push to firebase when there are no errors
  if (invalid.length === 0) {
    createProductRequest(values, imageAsFile);
  }
};

Upvotes: 1

Related Questions