Skip to main content

Avoiding Mistakes with Form Validation

Sometimes people forget to fill in the form properly. Let's help them by adding some basic checks.

// 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>}