Git Product home page Git Product logo

react-form-validator-core's Introduction

Validation component for react forms

license npm version Build Status

Simple form validation component for react forms inspired by formsy-react

Default validation rules:

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

Some rules can accept extra parameter, example:

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

Usage

import React from 'react';
import { ValidatorComponent } from 'react-form-validator-core';

class TextValidator extends ValidatorComponent {

    render() {
        const { errorMessages, validators, requiredError, validatorListener, ...rest } = this.props;

        return (
            <div>
                <input
                    {...rest}
                    ref={(r) => { this.input = r; }}
                />
                {this.errorText()}
            </div>
        );
    }

    errorText() {
        const { isValid } = this.state;

        if (isValid) {
            return null;
        }

        return (
            <div style={{ color: 'red' }}>
                {this.getErrorMessage()}
            </div>
        );
    }
}

export default TextValidator;
...
import { ValidatorForm } from 'react-form-validator-core';
...
render() {
    return (
        <ValidatorForm
            ref="form"
            onSubmit={this.handleSubmit}
        >
            <TextValidator
                onChange={this.handleChange}
                name="email"
                value={email}
                validators={['required', 'isEmail']}
                errorMessages={['this field is required', 'email is not valid']}
            />
            <button type="submit">submit</button>
        </ValidatorForm>
    );
}
...
...
import { ValidatorForm } from 'react-form-validator-core';
...
render() {
    return (
        <ValidatorForm
            ref="form"
            onSubmit={this.handleSubmit}
        >
            <TextValidator
                onChange={this.handleChange}
                name="file"
                type="file"
                value={file}
                validators={['isFile', 'maxFileSize:' + 1 * 1024 * 1024, 'allowedExtensions:image/png,image/jpeg']}
                errorMessages={['File is not valid', 'Size must not exceed 1MB', 'Only png and jpeg']}
            />
            <button type="submit">submit</button>
        </ValidatorForm>
    );
}
...

You can add your own rules

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

API

ValidatorForm

  • Props
Prop Required Type Default value Description
onSubmit true function Callback for form that fires when all validations are passed
instantValidate false bool true If true, form will be validated after each field change. If false, form will be validated only after clicking submit button.
onError false function Callback for form that fires when some of validations are not passed. It will return array of elements which not valid.
debounceTime false number 0 Debounce time for validation i.e. your validation will run after debounceTime ms when you stop changing your input
  • Methods
Name Params Return Descriptipon
resetValidations Reset validation messages for all validated inputs
isFormValid dryRun: bool (default true) Promise Get 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 (ValidatorComponent)

  • Props
Prop Required Type Default value Description
validators false array Array of validators. See list of default validators above.
errorMessages false array Array of error messages. Order of messages should be the same as validators prop.
name true string Name of input
validatorListener false function It triggers after each validation. It will return true or false
withRequiredValidator false bool Allow to use required validator in any validation trigger, not only form submit
  • Methods
Name Params Return Descriptipon
getErrorMessage Get error validation message
validate value: any, includeRequired: bool Run validation for current component
isValid bool Return current validation state
makeInvalid Set invalid validation state
makeValid Set valid validation state

Implemetations

Contributing

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

react-form-validator-core's People

Contributors

newoldmax avatar skorp avatar gigashiro avatar 7flow avatar ulisesbocchio avatar heberlz avatar jaimealvarezl avatar kizaonline avatar

Watchers

James Cloos avatar William Vilas Boas avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.