1.0.0 • Published 5 years ago

react-native-validator-form v1.0.0

Weekly downloads
64
License
MIT
Repository
github
Last release
5 years ago

Validation component for react-native forms

license npm version Build Status

Simple form validation component for React-Native inspired by formsy-react. Web version: react-material-ui-form-validator

Unfortunately I don't have Mac, so this library is tested only on Android.

Supported types:

  • TextInput

Default validation rules:

  • matchRegexp
  • isEmail
  • isEmpty
  • required
  • trim
  • isNumber
  • isFloat
  • isPositive
  • minNumber
  • maxNumber
  • minFloat
  • maxFloat
  • minStringLength
  • maxStringLength
  • isString

Some rules can accept extra parameter, example:

<TextValidator
   {...someProps}
   validators={['minNumber:0', 'maxNumber:255', 'matchRegexp:^[0-9]$']}
/>

Example

Usage

import React from 'react';
import { Button } from 'react-native';
import { Form, TextValidator } from 'react-native-validator-form';

class MyForm extends React.Component {
    state = {
        email: '',
    }

    handleChange = (email) => {
        this.setState({ email });
    }

    submit = () => {
        // your submit logic
    }

    handleSubmit = () => {
        this.refs.form.submit();
    }

    render() {
        const { email } = this.state;
        return (
            <Form
                ref="form"
                onSubmit={this.handleSubmit}
            >
                <TextValidator
                    name="email"
                    label="email"
                    validators={['required', 'isEmail']}
                    errorMessages={['This field is required', 'Email invalid']}
                    placeholder="Your email"
                    type="text"
                    keyboardType="email-address"
                    value={email}
                    onChangeText={this.handleChange}
                />
                 <Button
                    title="Submit"
                    onPress={this.handleSubmit}
                />
            </Form>
        );
    }
}

You can add your own rules

Form.addValidationRule('isPasswordMatch', (value) => {
    if (value !== this.state.user.password) {
        return false;
    }
    return true;
});

And remove them

componentWillUnmount() {
    Form.removeValidationRule('isPasswordMatch');
}

Usage

import React from 'react';
import { Button } from 'react-native';
import { Form, TextValidator } from 'react-native-validator-form';

class ResetPasswordForm extends React.Component {
    state = {
        user: {},
    }

    componentWillMount() {
        // custom rule will have name 'isPasswordMatch'
        Form.addValidationRule('isPasswordMatch', (value) => {
            if (value !== this.state.user.password) {
                return false;
            }
            return true;
        });
    }

    componentWillUnmount() {
        Form.removeValidationRule('isPasswordMatch');
    }

    handlePassword = (event) => {
        const { user } = this.state;
        user.password = event.nativeEvent.text;
        this.setState({ user });
    }

    handleRepeatPassword = (event) => {
        const { user } = this.state;
        user.repeatPassword = event.nativeEvent.text;
        this.setState({ user });
    }

    submit = () => {
        // your submit logic
    }

    handleSubmit = () => {
        this.refs.form.submit();
    }

    render() {
        const { user } = this.state;
        return (
            <Form
                ref="form"
                onSubmit={this.handleSubmit}
            >
                <TextValidator
                    name="password"
                    label="text"
                    secureTextEntry
                    validators={['required']}
                    errorMessages={['This field is required']}
                    type="text"
                    value={user.password}
                    onChange={this.handlePassword}
                />
                <TextValidator
                    name="repeatPassword"
                    label="text"
                    secureTextEntry
                    validators={['isPasswordMatch','required']}
                    errorMessages={['Password mismatch','This field is required']}
                    type="text"
                    value={user.repeatPassword}
                    onChange={this.handleRepeatPassword}
                />
                <Button
                    title="Submit"
                    onPress={this.handleSubmit}
                />
            </Form>
        );
    }
}
Advanced usage

API

Form

  • Props
PropRequiredTypeDefault valueDescription
onSubmittruefunctionCallback for form that fires when all validations are passed
instantValidatefalsebooltrueIf true, form will be validated after each field change. If false, form will be validated only after clicking submit button.
onErrorfalsefunctionCallback for form that fires when some of validations are not passed. It will return array of elements which not valid.
debounceTimefalsenumber0Debounce time for validation i.e. your validation will run after debounceTime ms when you stop changing your input
  • Methods
NameParamsReturnDescriptipon
resetValidationsReset validation messages for all validated inputs
isFormValiddryRun: bool (default true)PromiseGet form validation state in a Promise (true if whole form is valid). Run with dryRun = false to show validation errors on form

All validated fields (Input)

  • Props
PropRequiredTypeDefault valueDescription
validatorsfalsearrayArray of validators. See list of default validators above.
errorMessagesfalsearrayArray of error messages. Order of messages should be the same as validators prop.
nametruestringName of input
errorStylefalseobject{ container: { top: 0, left: 0, position: 'absolute' }, text: { color: 'red' }, underlineValidColor: 'gray', underlineInvalidColor: 'red' } }Error styles
validatorListenerfalsefunctionIt triggers after each validation. It will return true or false
withRequiredValidatorfalseboolAllow to use required validator in any validation trigger, not only form submit
  • Methods
NameParamsReturnDescriptipon
getErrorMessageGet error validation message
validatevalue: any, includeRequired: boolRun validation for current component
isValidboolReturn current validation state
makeInvalidSet invalid validation state
makeValidSet valid validation state

Contributing

This component covers all my needs, but feel free to contribute.