react-form-with-constraints
Simple form validation for React
Installation: npm install react-form-with-constraints
CDN: https://unpkg.com/react-form-with-constraints/dist/
Introduction: what is HTML5 form validation?
<form>
<label for="email">Email:</label>
<input type="email" id="email" required>
<button>Submit</button>
</form>
The required HTML5 attribute specifies that the user must fill in a value, type="email" checks that the entered text looks like an email address.
What react-form-with-constraints brings
- Minimal API and footprint
- Control HTML5 error messages:
<FieldFeedback when="valueMissing">My custom error message</FieldFeedback>
- Custom constraints:
<FieldFeedback when={value => ...}>
- Warnings and infos:
<FieldFeedback ... warning>
,<FieldFeedback ... info>
- Async validation
- No dependency beside React (no Redux, MobX...)
- No special component like
<TextField>
, just plain old<input>
or whatever you like - Re-render only what's necessary
- Support for React Native with npm package
react-form-with-constraints-native
- Easily extendable
- ...
<input type="password" name="password"
value={this.state.password} onChange={this.handleChange}
required pattern=".{5,}" />
<FieldFeedbacks for="password">
<FieldFeedback when="valueMissing" />
<FieldFeedback when="patternMismatch">
Should be at least 5 characters long
</FieldFeedback>
<FieldFeedback when={value => !/\d/.test(value)} warning>
Should contain numbers
</FieldFeedback>
<FieldFeedback when={value => !/[a-z]/.test(value)} warning>
Should contain small letters
</FieldFeedback>
<FieldFeedback when={value => !/[A-Z]/.test(value)} warning>
Should contain capital letters
</FieldFeedback>
<FieldFeedback when={value => !/\W/.test(value)} warning>
Should contain special characters
</FieldFeedback>
</FieldFeedbacks>
Examples
-
CodePen basic example: https://codepen.io/tkrotoff/pen/BRGdqL
-
CodeSandbox Bootstrap 4 example: https://codesandbox.io/s/qk0zro1qm4
-
CodeSandbox WizardForm example: https://codesandbox.io/s/my0ojyzq6p
-
CodeSandbox SignUp example: https://codesandbox.io/s/62qwozvm0k
-
CodeSandbox ClubMembers example: https://codesandbox.io/s/q8364yn60j
-
React Native example:
iOS Android
How it works
The API works the same way as React Router v4:
<Router>
<Route exact path="/" component={Home} />
<Route path="/news" component={NewsFeed} />
</Router>
It is also inspired by AngularJS ngMessages.
If you had to implement validation yourself, you would end up with a global object that tracks errors for each field.
react-form-with-constraints works similarly.
It uses React context to share the FieldsStore
object across FieldFeedbacks
and FieldFeedback
.
API
The API reads like this: "for field when constraint violation display feedback", example:
<FieldFeedbacks for="password">
<FieldFeedback when="valueMissing" />
<FieldFeedback when="patternMismatch">Should be at least 5 characters long</FieldFeedback>
</FieldFeedbacks>
for field "password"
when constraint violation "valueMissing" display "the HTML5 error message (*)"
when constraint violation "patternMismatch" display "Should be at least 5 characters long"
Async support works as follow:
<FieldFeedbacks for="username">
<Async
promise={checkUsernameAvailability} /* Function that returns a promise */
then={available => available ?
<FieldFeedback key="1" info style={{color: 'green'}}>Username available</FieldFeedback> :
<FieldFeedback key="2">Username already taken, choose another</FieldFeedback>
// Why key=*? React keys are needed otherwise it can get buggy when the user rapidly changes the input
}
/>
</FieldFeedbacks>
Trigger validation:
class MyForm extends React.Component {
async handleChange(e) {
const target = e.currentTarget;
// Validates only the given fields and returns Promise<Field[]>
const fields = await this.form.validateFields(target);
const fieldIsValid = fields.every(field => field.isValid());
if (fieldIsValid) console.log(`Field '${target.name}' is valid`);
else console.log(`Field '${target.name}' is invalid`);
if (this.form.isValid()) console.log('The form is valid');
else console.log('The form is invalid');
}
async handleSubmit(e) {
e.preventDefault();
// Validates the non-dirty fields and returns Promise<Field[]>
const fields = await this.form.validateForm();
// or simply this.form.isValid();
const formIsValid = fields.every(field => field.isValid());
if (formIsValid) console.log('The form is valid');
else console.log('The form is invalid');
}
render() {
return (
<FormWithConstraints
ref={formWithConstraints => this.form = formWithConstraints}
onSubmit={this.handleSubmit} noValidate
>
<input
name="username"
onChange={this.handleChange}
required minLength={3}
/>
<FieldFeedbacks for="username">
<FieldFeedback when="tooShort">Too short</FieldFeedback>
<Async
promise={checkUsernameAvailability}
then={available => available ?
<FieldFeedback key="1" info style={{color: 'green'}}>Username available</FieldFeedback> :
<FieldFeedback key="2">Username already taken, choose another</FieldFeedback>
}
/>
<FieldFeedback when="*" />
</FieldFeedbacks>
</FormWithConstraints>
);
}
}
-
for: string
=> reference to aname
attribute (e.g<input name="username">
), should be unique to the current formstop?: 'first' | 'first-error' | 'first-warning' | 'first-info' | 'no'
=>
when to stop renderingFieldFeedback
s, by default stops at the first error encountered (FieldFeedback
s order matters)
Note: you can place
FieldFeedbacks
anywhere, have as many as you want for the samefield
, nest them, mix them withFieldFeedback
... Dirty example:<div> <input name="username" ... /> </div> <FieldFeedbacks for="username" stop="first-warning"> <FieldFeedbacks stop="no"> <div> <FieldFeedbacks stop="first-error"> <FieldFeedbacks> <div><FieldFeedback ... /></div> <div><Async ... /></div> <div><FieldFeedback ... /></div> </FieldFeedbacks> </FieldFeedbacks> </div> <FieldFeedbacks> <FieldFeedback ... /> <Async ... /> <FieldFeedback ... /> <FieldFeedbacks stop="first-info"> <FieldFeedback ... /> <Async ... /> <FieldFeedback ... /> </FieldFeedbacks> <FieldFeedback ... /> <Async ... /> <FieldFeedback ... /> </FieldFeedbacks> </FieldFeedbacks> <FieldFeedbacks stop="first-info"> <FieldFeedbacks> <FieldFeedback ... /> <Async ... /> <FieldFeedback ... /> </FieldFeedbacks> </FieldFeedbacks> </FieldFeedbacks> <div> <FieldFeedbacks for="username" stop="no"> ... </FieldFeedbacks> </div>
-
when?
:ValidityState
as a string => HTML5 constraint violation name'*'
=> matches any HTML5 constraint violation'valid'
=> displays the feedback only if the field is valid(value: string) => boolean
=> custom constraint
error?: boolean
=> treats the feedback as an error (default)warning?: boolean
=> treats the feedback as a warninginfo?: boolean
=> treats the feedback as an infochildren
=> what to display when the constraint matches; if missing, displays the HTML5 error message if any
-
Async<T>
=> Async version ofFieldFeedback
, similar API as react-promisepromise: (value: string) => Promise<T>
=> a promise you want to wait forpending?: React.ReactNode
=> runs when promise is pendingthen?: (value: T) => React.ReactNode
=> runs when promise is resolvedcatch?: (reason: any) => React.ReactNode
=> runs when promise is rejected
-
-
validateFields(...inputsOrNames: Array<Input | string>): Promise<Field[]>
=>
Should be called when afield
changes, will re-render the properFieldFeedback
s (and update the internalFieldsStore
).
Without arguments, all fields ($('[name]')
) are validated. -
validateForm(): Promise<Field[]>
=>
Should be called before to submit theform
. Validates only all non-dirty fields (won't re-validate fields that have been already validated withvalidateFields()
),
If you want to force re-validate all fields, usevalidateFields()
without arguments. -
isValid(): boolean
=> should be called aftervalidateForm()
orvalidateFields()
, tells if the known fields are valid (thanks to internalFieldsStore
) -
reset(): Promise
=> resets internalFieldsStore
and re-render allFieldFeedback
s -
Field
=>{ name: string; validations: { key: number; type: 'error' | 'warning' | 'info' | 'whenValid'; show: boolean | undefined; }[]; // FieldFeedbackValidation[], isValid: () => boolean }
-