Coding exercise: create a login form with validation in React.

React practical coding · Freshers

Model answer

Use controlled inputs, validate on submit (and on blur if you want), show one clear message per field, and never trust the browser alone: the server must validate again.

function Login({ onLogin }) {
  const [form, setForm] = useState({ email: '', password: '' });
  const [errors, setErrors] = useState({});
  const validate = () => {
    const e = {};
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'Enter a valid email.';
    if (form.password.length < 8) e.password = 'Use at least 8 characters.';
    return e;
  };
  const submit = (ev) => {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length === 0) onLogin(form);
  };
  const set = (k) => (ev) => setForm({ ...form, [k]: ev.target.value });
  return (
    <form onSubmit={submit} noValidate>
      <label>Email <input type="email" value={form.email} onChange={set('email')} aria-invalid={!!errors.email} /></label>
      {errors.email && <p role="alert">{errors.email}</p>}
      <label>Password <input type="password" value={form.password} onChange={set('password')} aria-invalid={!!errors.password} /></label>
      {errors.password && <p role="alert">{errors.password}</p>}
      <button>Log in</button>
    </form>
  );
}

For bigger forms, mention React Hook Form with a schema library such as Zod.

Tips

Practise it yourself in the React and Angular code playground.

Learn this topic

React.js Full Course: Beginner to Advanced .

Sign in to add your own answer.

More questions