PROGRAMING/React

[REACT] Form Validator

donghunl 2024. 3. 6. 09:05
반응형

Validate a user sign-up form once the user submits that form.

 

Requirements :

The email password and password confirmation fields are all filled in. 

The email field must have exactly one @ sign in it. 

The password must be eight or more characters long. 

The password and the password confirmation field must be the same. 

 

if any of these conditions aren't met, you should display an error message.

If they're all met, instead, display a success message.

 

FromValidator.js

import { useState } from 'react'

export default function FormValidator() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [passwordConfirm, setPasswordConfirm] = useState('')

  const [message, setMessage] = useState('')

  const findErrors = () => {
    const errors = []

    if (!email || !password || !passwordConfirm) errors.push('All fields must be filled in')
    if ([...email].filter(i => i === '@').length !== 1) {
      errors.push('An email must have exactly on @ sign!')
    }
    if (password.length < 8) errors.push('The password must be eight or more characters long.')
    if (password !== passwordConfirm) errors.push('Password must match')

    return errors
  }
  const handleSubmit = e => {
    e.preventDefault()
    const errors = findErrors()
    setMessage(errors.length ? errors.join(', ') : 'User created!')
  }
  return (
    <form onSubmit={handleSubmit}>
      <h2>Sign Up!</h2>
      <label htmlFor='email'>Email</label>
      <input
        type='text' name='email'
        onChange={e => setEmail(e.target.value)}
      />
      <label htmlFor='password'>Password</label>
      <input
        type='password' name='password'
        onChange={e => setPassword(e.target.value)}
      />
      <label htmlFor='password-confirm'>Confirm Password </label>
      <input
        type='password' name='password-confirm'
        onChange={e => setPasswordConfirm(e.target.value)}
      />
      {message}
      <input type='submit' value='Submit' />
    </form>
  )
}

 

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

 

App.js

import FormValidator from './FormValidator'

function App () {
  return (
    <div className='App'>
      <FormValidator />
    </div>
  )
}

export default App

 

index.css

html, body {
  font-family: sans-serif;
}

.page {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
}

body {
  padding: 0px;
  margin: 0px;
}

input, label {
  display: block;
  margin: 8px auto;
}

input {
  padding: 8px;
  width: 300px;
}

input[type=submit] {
  width: 100px;
}

 

결과화면

 

 

error시 error message 표시

 

모든 조건이 맞을경우 User created! 메세지 표시

반응형