use-validator v2.0.0-alpha.1
Use-Validator
React library, using hooks to handle error message on input.
Installation
npm install use-validator
Validation Properties
- type
string
optional
( default will usecustom
type ):- alphabet
- alphanumeric
- length
- number
- required
- custom
- message
string
mandatory
- min
number
optional
( triggered by length type ) - max
number
optional
( triggered by length type ) - validate
function
optional
( 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
onvalidation
object is a callback function that take one parameter ( parameter value is input value that triggered byonChange
)
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:
1. To change single input you need to send first function argument as input event ( has target
property with HTMLInputElement or HTMLTextAreaElement interface).
setForm(inputEvent)
- To change multiple input you need to send first function argument as
object
typesetForm({ 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 test@email.com'
}
]
}
}
const [form, setForm] = useValidator(input)
const handleSetAllForm = () => {
setForm({
username: 'udin',
name: 'udin sedunia',
email: 'udin@sedunia.com'
})
}
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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago