RFV (React Form Validator)

React form validator and form handler.
RFV uses Validator.js as a validator engine, and Axios for HTTP requests.
Demo (Only form validator option)
Demo (Form validator and form handler option)

Installation
Install with Yarn.
$ yarn add rfv
Install with NPM.
$ npm i rfv
Usage
Only form validator option.
import React from 'react'
import ReactDOM from 'react-dom'
import { Form, Input, Textarea } from 'rfv'
const validations = {
email: [
{
rule: 'isEmail',
invalidFeedback: 'Please provide a valid email'
}
],
message: [
{
rule: 'isLength',
args: { min: 1 },
invalidFeedback: 'Please provide a message'
}
]
}
const App = () => {
const onSubmit = res => {
if (res.isFormValid) {
post('url', res.items)
}
}
return (
<Form onSubmit={onSubmit}>
<div>
<Input
type='email'
name='email'
validations={validations.email}
/>
</div>
<div>
<Textarea
name='message'
validations={validations.message}
/>
</div>
<div>
<button>Submit</button>
</div>
</Form>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
Form validator and form handler option.
import React from 'react'
import ReactDOM from 'react-dom'
import { Form, Input, Textarea } from 'rfv'
const validations = {
email: [
{
rule: 'isEmail',
invalidFeedback: 'Please provide a valid email'
}
],
message: [
{
rule: 'isLength',
args: { min: 1 },
invalidFeedback: 'Please provide a message'
}
]
}
const App = () => {
const postSubmit = res => {
console.log(res.data)
}
return (
<Form
postSubmit={postSubmit}
postOptions={{ method: 'post', url: 'url' }}
>
<div>
<Input
type='email'
name='email'
validations={validations.email}
/>
</div>
<div>
<Textarea
name='message'
validations={validations.message}
/>
</div>
<div>
<button>Submit</button>
</div>
</Form>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
And add .is-invalid
and .invalid-feedback
classes into your CSS.
.is-invalid {
border: 1px solid #dc3545;
}
.invalid-feedback {
display: none;
color: #dc3545;
}
.is-invalid ~ .invalid-feedback {
display: block;
}
Make sure you add the errors to the validations
object in backend.
app.post('/sign-up', (req, res) => {
const result = {
validations: {}
}
if (req.body.username === 'john') {
result.validations.username = 'john is already registered'
}
res.send(result)
})
Props & Callbacks
<Form>
Props
<Form
runValidation={true|false}
postOptions={{
url: 'url',
method: 'post',
headers: {
'Authorization': 'Token ...'
}
}}
>
Callbacks
<Form
removeItems={['key1', 'key2']}
preSubmit={res => {
}}
onSubmit={res => {
}}
postSubmit={res => {
}}
>
<Input>
, <Select>
, <Textarea>
Props
<Input
validations={[
{
rule: 'isLength',
args: { min: 1 },
invalidFeedback: 'Please provide a username'
},
{
rule: 'isLength',
args: { min: 4, max: 32 },
invalidFeedback: 'Username must be minimum 4, maximum 32 characters'
}
]}
/>
Callbacks
<Input
onChange={res => {
}}
/>
Contribution
Feel free to contribute. Open a new issue, or make a pull request.
License
MIT