rule

Specification

A synchronous rule applied to the field as the top priority validation. When the rule rejects, all the remaining validation chain is ignored.

Definition

1
type Rule = RegExp | (params) => boolean
Copied!

Parameters

The following parameters are exposed to the rule when it is a function:
Parameter name
Type
Description
get
Function
Reactive props getter function.
value
any
The current value of the field.
fieldProps
Object
Props of the current field.
fields
Object
Map of all fields.
form
Object
A reference to the current Form

Example

Regular expression

1
import React from 'react'
2
import { Form } from 'react-advanced-form'
3
import { Input } from 'react-advanced-form-addons'
4
5
export default class Example extends React.Component {
6
render() {
7
return (
8
<Form>
9
<Input
10
name="username"
11
rule={/^\d+/} />
12
</Form>
13
)
14
}
15
}
Copied!

Resolver function

1
import React from 'react'
2
import { Form } from 'react-advanced-form'
3
import { Input } from 'react-advanced-form-addons'
4
5
export default class Example extends React.Component {
6
validateUsername = ({ get, value, fieldProps, fields, form }) => {
7
/* "username" is valid only when equals to "foo" */
8
return value === 'foo'
9
}
10
11
render() {
12
return (
13
<Form>
14
<Input
15
name="username"
16
rule={this.validateUsername} />
17
</Form>
18
)
19
}
20
}
Copied!

Reactive rule

1
import React from 'react'
2
import { Form } from 'react-advanced-form'
3
import { Input } from 'react-advanced-form-addons'
4
5
export default class Example extends React.Component {
6
render() {
7
return (
8
<Form>
9
<Input
10
name="password"
11
type="password"
12
required />
13
<Input
14
name="confirmPassword"
15
rule={({ get, value }) => {
16
/* Valid only when equals to "password" field's value */
17
return value === get(['password', 'value'])
18
}}
19
required />
20
</Form>
21
)
22
}
23
}
Copied!
Read more about Reactive props feature, it is a game-changer.
Last modified 3yr ago