Skip to main content

Form Validation

What is Form Validation ?

Sometimes people forget to fill in the form properly. Form validation will help them by adding some basic checks to make sure that people will fill the form correctly.

[addWe moreuse pictureRegex najaa](Regular Expression) to validate our data.

// Imagine this is added to SimpleForm.js
// ...

const [email, setEmail] = useState('');
const [emailError, setEmailError] = useState('');

// ...

const validateEmail = (value) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  const isValid = emailRegex.test(value);

  setEmailError(isValid ? '' : 'Invalid email address');
};

const handleChange = (event) => {
  const value = event.target.value;
  setEmail(value);
  validateEmail(value);
};

// ...

<button type="submit" disabled={!!emailError}>
  Submit
</button>

{emailError && <span style={{ color: "red" }}>{emailError}</span>}
{!emailError && email && <span style={{ color: "green" }}>Valid</span>}

The regular expression /^[^\s@]+@[^\s@]+\.[^\s@]+$/ checks if the provided email address adheres to the following rules:

  • ^[^\s@]+: The email must start with one or more characters that are not whitespaces (\s) or '@'.

  • @: There must be a single '@' symbol in the email address.

  • [^@]+: Following the '@' symbol, there must be one or more characters that are not '@'.

  • \.: There must be a dot '.' after the '@' symbol and its subsequent characters.

  • [^\s@]+$: The email must end with one or more characters that are not whitespaces or '@'.

As you see the result below, the email is invalid because it does not match the regular expression to add dot after @

1706259802988.png

If the data is match the Regex, that data is validate as a valid likes this:

1706259826809.png