Welcome to the @cat-react/form
API documentation.
- Form (Main Component)
- Input (HOC for building input fields)
- Retrieves
- Passes Down
- reset
- Validation Rules (StandardSet shipping with
@cat-react/form
)
Main Component for building a form.
import {Form} from '@cat-react/form';
A static
method to add global validation rules.
name | Name of the validation rule. |
func | Function containing the validation logic of the rule. |
createsDependencies | Indicates if the rule should create dependencies to the fields which are passed as rule conditions. |
import {Form} from '@cat-react/form';
Form.addValidationRule('equalsUpperCase', (values, value, otherFieldName) {
return values[otherFieldName].toUpperCase() === value;
}, true);
render() {
<Form ...>
<BasicInput name="field1"
value="a"
.../>
<BasicInput name="field2"
value="A" //valid
validations={{
equalsUpperCase: 'field1'
}}/>
<BasicInput name="field2"
value="a" //invalid
validations={{
equalsUpperCase: 'field1'
}}/>
</Form>
}
Method which is being called when a submit event is fired on the form, regardless of whether the form is valid or invalid.
values | All form values as a Map. |
valid | Boolean which indicates if the form is valid or invalid. |
submit(values, valid) {
console.log(values); // { field1: "a", field2: "b" }
console.log(valid); // true or false
}
render() {
<Form onSubmit={this.submit}>
<BasicInput name="field1"
value="a"
.../>
<BasicInput name="field2"
value="b"
.../>
</Form>
}
Method which is being called when a submit event is fired on the valid form.
values | All form values as a Map. |
validSubmit(values) {
...
}
render() {
<Form onValidSubmit={this.validSubmit}>
...
</Form>
}
Method which is being called when a submit event is fired on the invalid form.
values | All form values as a Map. |
invalidSubmit(values) {
...
}
render() {
<Form onInvalidSubmit={this.invalidSubmit}>
...
</Form>
}
Method which is being called when the form state changes. As an example you can use it to disable the submit button when the form is invalid.
valid | Boolean which indicates if the form is valid or invalid. |
values | All form values as a Map. |
isValidating | Boolean which indicates if the form is validating or already finished with the validation. Always false if the state is valid. |
constructor(props) {
super(props);
this.validChanged = this.validChanged.bind(this);
this.state = {
canSubmit: false
};
}
validChanged(valid) {
this.setState({
canSubmit: valid
});
}
render() {
<Form onValidChanged={this.validChanged}>
...
<button type="submit" disabled={!this.state.canSubmit}>Submit</button>
</Form>
}
Method which is being called when the form state changes to valid.
values | All form values as a Map. |
valid(values) {
...
}
render() {
<Form onValid={this.valid}>
...
</Form>
}
Method which is being called when the form state changes to invalid.
values | All form values in as a Map. |
isValidating | Boolean which indicates if the form is validating or already finished with the validation. |
inValid(values, isValidating) {
...
}
render() {
<Form onInvalid={this.inValid}>
...
</Form>
}
CSS ClassName which will be passed directly to the
html element.For example:
<Form className="test" />
will result in:
<form class="test" />
AutoComplete prop which will be passed directly to the html element.
For example:
<Form autoComplete="off" />
will result in:
<form autocomplete="off" />
Specifies the timeout after which an input validations starts in milliseconds. Default is 350.
This is useful so that the user doesn't get interrupted with validation messages while he is typing. Also helpful for asynchronous validations because the server doesn't get polluted with requests on every keystroke.
Can be overwritten with the changeValueTimeout prop on an Input.
Resets all child inputs with their value prop. For more information go to the Input reset section.
render() {
<Form ref={(form) => this.form = form}>
...
</Form>
<button type="button" onClick={() => this.form.reset()}>Reset</button>
}
It's also possible to pass a map with values for each input. Each Input will be resetting to the given value (or its prop value if none is provided).
Example:
render() {
<Form ref={(form) => this.form = form}>
<BasicInput name="field1"/>
</Form>
<button type="button" onClick={() => this.form.reset({field1:'newvalue'})}>Reset</button>
}
Higher-Order Component for building input fields.
Example BasicInput using the HOC with an decorator:
import {Input} from '@cat-react/form';
@Input
class BasicInput extends React.Component {
constructor(props) {
this.onChange = this.onChange.bind(this);
}
onChange(event) {
// setValue method passed down from the HOC, used to update its value
this.props.setValue(event.target.value);
}
render() {
return (
<input type="text"
value={this.props.getValue()}
onChange={this.onChange}/>
);
}
}
All validation rules run against the value of the HOC which is being set with the setValue prop.
Props which should be passed down to the HOC.
Value of the Input.
Can also be used as a static default value. The HOC has its own state of the value (for validation purpose) which means you can let it take responsibility of it and retrieve it with the submit events.
<BasicInput value="abc"/>
<BasicInput value={10}/>
Name of the Input. Must be unique, per form should only be one input field with a specific name.
<BasicInput name="field1"/>
The validations rules which have to succeed in order to successfully submit the form. (If they are not marked as a warning)
You can either use global rules or custom inline rules.
<BasicInput name="password"
validations={{
isRequired: true,
customRule: (values, value) => {
return (value !== 'password');
}
}}/>
<BasicInput name="confirm_password"
validations={{
isRequired: true,
equalsField: 'password'
}}/>
The validation rules which should be treated as a warning only. (If they fail, the form is valid either)
<BasicInput name="confirm_password"
validations={{
isRequired: true,
equalsField: 'password'
}}
warnings={['isRequired']}/>
The (error-)messages of the validation rules which fail. Also being passed down for validationRules marked as a warning.
<BasicInput name="password"
validations={{
isRequired: true,
customRule: (values, value) => {
return (value !== 'password');
}
}}
messages={{
isRequired: 'You have to fill the password field.',
customRule: '"password" is not a valid password.'
}}/>
The manually added dependencies to other fields. The field will also be revalidated when one the dependency-fields changes.
Especially necessary if you use custom rules which create dependencies to other fields and do not autogenerate them.
<BasicInput name="password" />
<BasicInput name="confirm_password"
validations={{
isRequired: true,
equalsPassword: (values, value) => {
return values.password === value;
}
}}
dependencies={['password']}/> // if password is being changed you want that confirm_password will also be revalidated
Warning: You don't have to define such dependencies for global rules like equalsField
. Those global rules create the dependencies automatically.
Specifies the timeout after which an input validations starts in milliseconds.
For more information take a look at the form changeValueTimeout prop.
This prop can be used to overwrite the form prop for each input.
Props which are passed down to your custom input which uses the HOC. Additonally all props which are being passed to the HOC will also be passed down.
Method which tells the wrapped component if the field is required.
Example: you can use it to show a (*) sign for required fields beneath the label
render() {
let requiredSign = '';
if (this.props.isRequired()) {
requiredSign = ' *';
}
return (
<div>
<label>Label{requiredSign}</label>
<input type="text" ... />
</div>
)
}
Tells the wrapped component if the field is pristine. (wasn't touched yet)
Example: only show messages if field is not pristine.
renderMessages() {
let messages = [];
if (!this.props.isPristine()) {
messages = this.props.getMessages();
}
if (!messages || messages.length <= 0) {
return null;
}
return <ul>{messages.map((message, i) => <li key={i}>{message}</li>)}</ul>;
}
Tells the wrapped component if (the value of) the field is valid.
Example: style messages differently if there are warnings
renderMessages() {
let messages = this.props.getMessages();
if (!messages || messages.length <= 0) {
return null;
}
let className = 'errorText';
if (this.props.isValid()) {
className = 'warningText';
}
return <ul>{messages.map((message, i) => <li key={i}>{message}</li>)}</ul>;
}
Returns the current value of the field.
render() {
return <input value={this.props.getValue()} ... />;
}
Sets the value of the field. Revalidation is being done afterwards.
import {Input} from '@cat-react/form';
@Input
class BasicInput extends React.Component {
constructor(props) {
this.onChange = this.onChange.bind(this);
}
onChange(event) {
this.props.setValue(event.target.value);
}
render() {
return (
<input onChange={this.onChange} ... />
);
}
}
Returns the error messages. If the field is valid, but also has messages, you can assume it's a warning, not an error.
renderMessages() {
let messages = this.props.getMessages();
if (!messages || messages.length <= 0) {
return null;
}
return <ul>{messages.map((message, i) => <li key={i}>{message}</li>)}</ul>;
}
Touches the component. Helpful if you want to show error messages only on touched input errors, just trigger it onBlur
.
render() {
return <input onBlur={this.props.touch} ... />;
}
Resets the input with the given value. If no value is provided, it will be resetted to the current "this.props.value" of the input. The input is pristine (untouched) after resetting.
render() {
<Form>
<BasicInput ref={(input) => this.input = input}/>
</Form>
<button type="button" onClick={() => this.input.reset('')}>Reset Input</button>
}
StandardSet of validation rules which ships with @cat-react/form
.
Field has to match the given regex.
<BasicInput validations={{
matchRegexp: /ab*c/
}}/>
Field is required - the value must not be undefined, null, empty.
<BasicInput validations={{
isRequired: true
}}/>
Field value has to be a valid email address.
<BasicInput validations={{
isEmail: true
}}/>
The minimum length of the value has to be the given param.
<BasicInput validations={{
minLength: 3
}}/>
The maximum length of the value has to be the given param.
<BasicInput validations={{
maxLength: 3
}}/>
The value has to equal the given param.
<BasicInput validations={{
equals: 'test'
}}/>
The value has to equal the value of the field with the given name.
Creates dependencies.
<BasicInput validations={{
equalsField: 'password' // fieldName: password
}}/>
The value has to equal the values of the fields with the given names.
Creates dependencies.
<BasicInput validations={{
equalsFields: ['password1', 'password2'] // fieldName: password1, password2
}}/>
The value has to be a number.
<BasicInput validations={{
isNumber: true
}}/>