Skip to content
This repository has been archived by the owner on Feb 29, 2024. It is now read-only.

Latest commit

 

History

History
731 lines (603 loc) · 16.8 KB

api.md

File metadata and controls

731 lines (603 loc) · 16.8 KB

API Documentation

Welcome to the @cat-react/form API documentation.

Table of Contents


Form

Main Component for building a form.

import {Form} from '@cat-react/form';

addValidationRule(name, func, createsDependencies)

A static method to add global validation rules.

Params

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.

Example

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>
}

onSubmit(values, valid)

Method which is being called when a submit event is fired on the form, regardless of whether the form is valid or invalid.

Params

values All form values as a Map.
valid Boolean which indicates if the form is valid or invalid.

Example

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>
}

onValidSubmit(values)

Method which is being called when a submit event is fired on the valid form.

Params

values All form values as a Map.

Example

validSubmit(values) {
    ...
}

render() {
    <Form onValidSubmit={this.validSubmit}>    
        ...
    </Form>
}

onInvalidSubmit(values)

Method which is being called when a submit event is fired on the invalid form.

Params

values All form values as a Map.

Example

invalidSubmit(values) {
    ...
}

render() {
    <Form onInvalidSubmit={this.invalidSubmit}>    
        ...
    </Form>
}

onValidChanged(valid, values, isValidating)

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.

Params

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.

Example

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>
}

onValid(values)

Method which is being called when the form state changes to valid.

Params

values All form values as a Map.

Example

valid(values) {
    ...
}

render() {
    <Form onValid={this.valid}>    
        ...
    </Form>
}

onInvalid(values, isValidating)

Method which is being called when the form state changes to invalid.

Params

values All form values in as a Map.
isValidating Boolean which indicates if the form is validating or already finished with the validation.

Example

inValid(values, isValidating) {
    ...
}

render() {
    <Form onInvalid={this.inValid}>    
        ...
    </Form>
}

className

CSS ClassName which will be passed directly to the

html element.

For example:

<Form className="test" />

will result in:

<form class="test" />

autoComplete

AutoComplete prop which will be passed directly to the html element.

For example:

<Form autoComplete="off" />

will result in:

<form autocomplete="off" />

changeValueTimeout

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.

reset

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>
}

Input

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.

Retrieves

Props which should be passed down to the HOC.

value

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

Name of the Input. Must be unique, per form should only be one input field with a specific name.

<BasicInput name="field1"/>

validations

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'
            }}/>

warnings

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']}/>

messages

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.'
            }}/>

dependencies

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.

changeValueTimeout

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.


Passes Down

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.

isRequired

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>
    )
}

isPristine

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>;
}

isValid

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>;
}

getValue

Returns the current value of the field.

render() {
    return <input value={this.props.getValue()} ... />;
}

setValue

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} ... />
        );
    }
}

getMessages

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>;
}

touch

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} ... />;
}

reset(value)

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>
}

Validation Rules

StandardSet of validation rules which ships with @cat-react/form.

matchRegexp

Field has to match the given regex.

<BasicInput validations={{
                matchRegexp: /ab*c/
            }}/>

isRequired

Field is required - the value must not be undefined, null, empty.

<BasicInput validations={{
                isRequired: true
            }}/>

isEmail

Field value has to be a valid email address.

<BasicInput validations={{
                isEmail: true
            }}/>

minLength

The minimum length of the value has to be the given param.

<BasicInput validations={{
                minLength: 3
            }}/>

maxLength

The maximum length of the value has to be the given param.

<BasicInput validations={{
                maxLength: 3
            }}/>

equals

The value has to equal the given param.

<BasicInput validations={{
                equals: 'test'
            }}/>

equalsField

The value has to equal the value of the field with the given name.

Creates dependencies.

<BasicInput validations={{
                equalsField: 'password' // fieldName: password
            }}/>

equalsFields

The value has to equal the values of the fields with the given names.

Creates dependencies.

<BasicInput validations={{
                equalsFields: ['password1', 'password2'] // fieldName: password1, password2
            }}/>

isNumber

The value has to be a number.

<BasicInput validations={{
                isNumber: true
            }}/>