use-validator
v2.0.0-alpha.1
Published
React library, using hooks to handle error message on input.
Readme
Use-Validator
React library, using hooks to handle error message on input.
Installation
npm install use-validator
Validation Properties
- type
stringoptional( default will usecustomtype ):- alphabet
- alphanumeric
- length
- number
- required
- custom
- message
stringmandatory - min
numberoptional( triggered by length type ) - max
numberoptional( triggered by length type ) - validate
functionoptional( triggered by custom type)
Usage
input argument should object and always have three properties value, error and validator,
value: input value
error: error message
validator: is array of object of
validation
validate property on validation object is a callback function that take one parameter ( parameter value is input value that triggered by onChange)
useValidator will return array same as react hooks, first index is input value, and second index is function to change value on first index.
second index is a function that has two usage:
- To change single input you need to send first function argument as input event ( has
targetproperty with HTMLInputElement or HTMLTextAreaElement interface).
setForm(inputEvent)- To change multiple input you need to send first function argument as
objecttype
setForm({ name: 'myName', username: 'myUsername', email: 'myEmail' })Demo: CodeSandbox
import useValidator from 'use-validator';
function App(){
const input = {
username: {
value: '',
error: '',
validator: [
{
type: 'alphabet',
message: 'letter only'
},
{
type: 'length',
min: 3,
max: 10,
message: 'min 3 max 10 words'
},
{
type: 'required',
message: 'username can\'t be empty'
}
]
},
name: {
value: '',
error: '',
validator: [
{
validate: text => /^[A-Z]/.test(text),
message: 'first letter should be capital'
},
{
validate: text => /^[a-zA-Z ]+$/.test(text),
message: 'letter and space only'
},
{
type: 'length',
min: 5,
max: 20,
message: 'min 5 max 20 words'
}
]
},
email: {
value: '',
error: '',
validator: [
{
type: 'email',
message: 'input should look like [email protected]'
}
]
}
}
const [form, setForm] = useValidator(input)
const handleSetAllForm = () => {
setForm({
username: 'udin',
name: 'udin sedunia',
email: '[email protected]'
})
}
return(
<div>
username:
<input name="username" value={form.username.value} onChange={(e) => setForm(e)}/>
<p>{form.username.error}</p>
name:
<input name="name" value={form.name.value} onChange={setForm}/>
<p>{form.name.error}</p>
email:
<input name="email" value={form.email.value} onChange={setForm}/>
<p>{form.email.error}</p>
<button onClick={handleSetAllForm}>Set Multiple Form</button>
</div>
)
}
export default App
