Skip to content

Instantly share code, notes, and snippets.

@highercomve
Last active February 18, 2019 20:48
Show Gist options
  • Select an option

  • Save highercomve/ad7e6c8abddb75d2a6b9b0175f53c349 to your computer and use it in GitHub Desktop.

Select an option

Save highercomve/ad7e6c8abddb75d2a6b9b0175f53c349 to your computer and use it in GitHub Desktop.
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
function UserForm () {
const [errors, setErrors] = useState({})
const submit = (event) => {
event.preventDefault()
const form = event.target
const isValid = form.checkValidity() // returns true or false
const formData = new FormData(form)
const validationMessages = Array.from(formData.keys()).reduce((acc, key) => {
acc[key] = form.elements[key].validationMessage
return acc
}, {})
setErrors(validationMessages)
console.log({
validationMessages,
data,
isValid
})
if (isValid) {
// here you do what you need to do if is valid
const data = Array.from(formData.keys()).reduce((acc, key) => {
acc[key] = formData.get(key)
return acc
}, {})
}
}
const onInput = (event) => {
const input = event.target
const isValid = input.checkValidity
setErrors({ ...errors, [input.name]: input.validationMessage })
}
const hasError = (field) => !!errors[field]
const getError = (field) => errors[field]
return (
<form className='validated-form' noValidate onSubmit={submit}>
<div className={ hasError('firstName') ? 'validated-form__control error' : 'validated-form__control' }>
<label htmlFor='firstName'>First name</label>
<input
onInput={onInput}
type='text'
name='firstName'
id='firstName'
minLength='2'
pattern='[a-zA-Z]*'
required
autoComplete='on'/>
<div className='validated-form__errors'>{getError('firstName')}</div>
</div>
<div className={ hasError('lastName') ? 'validated-form__control error' : 'validated-form__control' }>
<label htmlFor='lastName'>Last name</label>
<input
onInput={onInput}
type='text'
name='lastName'
id='lastName'
required />
<div className='validated-form__errors'>{getError('lastName')}</div>
</div>
<div className={ hasError('age') ? 'validated-form__control error' : 'validated-form__control' }>
<label htmlFor='age'>Age</label>
<input
onInput={onInput}
type='number'
name='age'
max='90'
min='18'
step='1'
id='age'
pattern='\d+'
required
autoComplete='on'/>
<div className='validated-form__errors'>{getError('age')}</div>
</div>
<div className={ hasError('email') ? 'validated-form__control error' : 'validated-form__control' }>
<label htmlFor='email'>Email</label>
<input
onInput={onInput}
type='email'
name='email'
id='email'
required />
<div className='validated-form__errors'>{getError('email')}</div>
</div>
<div className='validated-form__actions'>
<button className='btn' type='submit' >Submit</button>
</div>
</form>
)
}
ReactDOM.render(
<div>
<UserForm />
</div>,
document.getElementById('root')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment