1.1.1 • Published 4 years ago
react-html-form-validation-hook v1.1.1
React HTML Form Validation Hook
React hook that facilitates use of constraint-based form field validation and showing error messages.
This hook provides you the option of associating form validation rules directly with form elements.
Usage
import React, { UseState } from 'react';
import { useHtmlFormValidation } from 'react-html-form-validation-hook';
const handleSubmit = values => {
// ...
};
const MyComponent = props => {
const [name, setName] = useState();
const [age, setAge] = useState();
const { errors, handleFieldFocus, handleFieldBlur } = useHtmlFormValidation();
return (
<form noValidate onSubmit={handleSubmit}>
<div>
<label for="name">Name</label>
<input
id="name"
placeholder="Enter a name"
value={name}
onFocus={handleFieldFocus('name')}
onBlur={handleFieldBlur('name')}
required
onChange={event => setName(event.target.value)}
/>
{errors.name && <small>{errors.name}</small>}
</div>
<div>
<label for="age">Age</label>
<input
id="age"
value={age}
min={0}
step={1}
inputMode="numeric"
onFocus={handleFieldFocus('age')}
onBlur={handleFieldBlur('age')}
required
onChange={event => setAge(event.target.value)}
/>
{errors.age && <small>{errors.age}</small>}
</div>
</form>
);
};
This is very basic. Currently this hook does not support whether fields are focused, touched, dirty, or pristine. If you'd like to add this functionality, please feel free to send a pull request.