Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-form-validator-core

Package Overview
Dependencies
Maintainers
0
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-form-validator-core

Core validator component for react forms.

  • 2.0.1
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
0
Created
Source

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
  • isString
  • minStringLength
  • maxStringLength
  • 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>
    );
}
...

class FileValidator extends ValidatorComponent {
  render() {
    const { errorMessages, validators, requiredError, validatorListener, value, ...rest } = this.props;
    return (
      <div>
        <input type="file" {...rest}>
        {this.errorText()}
      </div>
    );
  }

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

    if (isValid) {
      return null;
    }

    return <div style={{ color: "red" }}>{this.getErrorMessage()}</div>;
  }
}
export default FileValidator;

...
import { ValidatorForm } from 'react-form-validator-core';
...
render() {
    return (
        <ValidatorForm
            ref="form"
            onSubmit={this.handleSubmit}
        >
            <FileValidator
                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;
});

Get them

ValidatorForm.getValidationRule('isPasswordMatch');

Remove them

ValidatorForm.removeValidationRule('isPasswordMatch');

And check is validation rule already in list

ValidatorForm.hasValidationRule('isPasswordMatch');

Migration guide

From 0.x to 1.x

Breaking changes was introduced in order to avoid legacy context. You should change render method of your input components to renderValidatorComponent.

Before:

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

class TextValidator extends ValidatorComponent {
    render() {
        // return your validated component
    }
}

export default TextValidator;

After:

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

class TextValidator extends ValidatorComponent {
    renderValidatorComponent() {
        // return your validated component
    }
}

export default TextValidator;

API

ValidatorForm
  • 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
  • Instance methods (via ref)
NameParamsReturnDescription
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
  • Static methods (via class)
NameParamsReturnDescription
addValidationRulename: string, callback: functionAdd new validation rule
getValidationRulename: stringfunctionGet validation rule by name
hasValidationRulename: stringboolCheck if rule exsits
removeValidationRulename: stringRemove validation rule
All validated fields (ValidatorComponent)
  • 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
validatorListenerfalsefunctionIt triggers after each validation. It will return true or false
withRequiredValidatorfalseboolAllow to use required validator in any validation trigger, not only form submit
containerPropsfalseobjectAllow to customize input wrapper div
  • Methods
NameParamsReturnDescription
getErrorMessageGet error validation message
validatevalue: any, includeRequired: boolRun validation for current component
isValidboolReturn current validation state
makeInvalidSet invalid validation state
makeValidSet valid validation state

Implementations

Contributing

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

Keywords

FAQs

Package last updated on 23 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc