Coder Social home page Coder Social logo

moeen-basra / ree-validate Goto Github PK

View Code? Open in Web Editor NEW
16.0 2.0 4.0 2.92 MB

Simple React.js input validation plugin extended from vee-validate

License: MIT License

JavaScript 99.90% Shell 0.10%
react laravel validation react-validate reactjs

ree-validate's Introduction

VeeValidate is a library for React.js that allows you to validate input fields, and display errors.

This plugin is inspired by PHP Framework Laravel's validation.

Installation

npm

npm install ree-validate --save

yarn

yarn add ree-validate

Getting Started

import ReeValidate from 'ree-validate'

install classnames for easily manage the classes

npm i -S classnames

import classnames from 'classnames'

Now create a new class and bind errors bag with state.

class Page extends Component {
  constructor(props) {
    super(props)
    
    this.validator = new ReeValidate.Validator({
      email: 'required|email',
      password: 'required|min:3',
    })
    
    this.state = {
      formData: {
        email: '',
        password: '',
      },
      errors: this.validator.errors,
    }
    
    this.onChange = this.onChange.bind(this)
    this.validateAndSubmit = this.validateAndSubmit.bind(this)
  }
  
  onChange(e) {
    const name = e.target.name
    const value = e.target.value
    const { errors } = this.validator
    
    // reset errors for url field
    errors.remove(name)
    
    // update form data
    this.setState({ formData: { ...this.state.formData, [name]: value } })
    
    this.validator.validate(name, value)
      .then(() => {
        this.setState({ errors })
      })
  }
  
  submit(formData) {
    console.log(formData)
  }
  
  async validateAndSubmit(e) {
    e.preventDefault()
    
    const { formData } = this.state
    const { errors } = this.validator

    const valid = this.validator.validateAll(formData)
    
    if (valid) {
        this.submit(formData)
    } else {
        this.setState({ errors })        
    }    
  }
  
  render() {
    const { errors } = this.state
    
    return (<form id="sign_in" onSubmit={this.validateAndSubmit}>
      <div className="msg">Sign in to start your session</div>
      <div className="input-group">
                <span className="input-group-addon">
                    <i className="material-icons">person</i>
                </span>
        <div className={classnames('form-line', { 'error':  errors.has('email')})}>
          <input type="email"
                 id="email"
                 className="form-control"
                 name="email"
                 placeholder="Email"
                 required
                 onChange={this.onChange}
                 autoFocus/>
        </div>
        { errors.has('email') &&
        <label id="name-error" className="error" htmlFor="email">{ errors.first('email') }</label>
        }
      </div>
      <div className="input-group">
                <span className="input-group-addon">
                    <i className="material-icons">lock</i>
                </span>
        <div className={classnames('form-line', { 'error':  errors.has('password')})}>
          <input type="password"
                 id="password"
                 className="form-control"
                 name="password"
                 placeholder="Password"
                 required
                 onChange={this.onChange}/>
        </div>
        { errors.has('password') &&
        <label id="name-error" className="error" htmlFor="password">{ errors.first('password') }</label>
        }
      </div>
      <div className="row">
        <div className="col-xs-8 p-t-5">
          <input type="checkbox" name="rememberme" id="rememberme" className="filled-in chk-col-pink"/>
          <label htmlFor="rememberme">Remember Me</label>
        </div>
        <div className="col-xs-4">
          <button className="btn btn-block bg-pink waves-effect" type="submit">SIGN IN</button>
        </div>
      </div>
      <div className="row m-t-15 m-b--20">
        <div className="col-xs-6">
          <a href="sign-up.html">Register Now!</a>
        </div>
        <div className="col-xs-6 align-right">
          <a href="forgot-password.html">Forgot Password?</a>
        </div>
      </div>
    </form>)
  }
}

export default Page

Changing the locale for ReeValidate

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import ReeValidate from 'ree-validate'
import fr from 'ree-validate/dist/locale/fr'
class Page extends Component {
    static displayName = 'RegisterPage'
    static propTypes = {
        // validate props
    }

    constructor(props) {
        super(props)

        this.validator = new ReeValidate.Validator({
            email: 'required|email',
            password: 'required|min:6'
        })

        this.validator.localize('fr', fr)
    }

   render() {
        // render component
    }
}

export default Page

HOC

You can also use the following hoc

note: it is not yet part of the package

import * as React from 'react'
import { Validator } from 'ree-validate'

export default function withValidator(Component, fields){
  class withValidator extends React.Component{

    validator = new Validator()

    _isMounted = false

    constructor(props: any) {
      super(props)

      this.attachRules(fields)

      this.state = {
        errors: this.validator.errors,
      }
    }

    componentDidMount() {
      this._isMounted = true
    }

    componentWillUnmount() {
      this._isMounted = false
    }

    validateAll = async (data: any) => {
      const { errors } = this.validator

      for (let fieldName in data) {
        if (data.hasOwnProperty(fieldName)) {
          if (errors.has(fieldName)) {
            errors.remove(fieldName)
          }
        }
      }

      const isValid = await this.validator.validateAll(data)

      if (this._isMounted) {
        this.setState({ errors })
      }

      return isValid
    }
    validateOne = async ({ name, value }: { name: string, value: any }) => {
      const { errors } = this.validator

      if (errors.has(name)) {
        errors.remove(name)
      }

      const isValid = await this.validator.validate(name, value)

      if (this._isMounted) {
        this.setState({ errors })
      }

      return isValid
    }

    validate = (data: any, multi: boolean = true) => {
      if (multi) {
        return this.validateAll(data)
      }
      return this.validateOne(data)
    }

    clearErrors = (fieldName: ?string) => {
      const { errors } = this.validator

      if (fieldName) {
        errors.remove(fieldName)
      } else {
        errors.clear()
      }

      if (this._isMounted) {
        this.setState({ errors })
      }
    }

    attachRules = (field: Field | Array<Field>) => {
      if (isArray(field)) {
        field.forEach((f: Field) => {
          this.attachRules(f)
        })
      } else {
        this.detachRules(field)

        this.validator.attach(field)
      }
    }

    detachRules = (field: Field | Array<Field>) => {
      if (isArray(field)) {
        field.forEach((f: Field) => {
          this.detachRules(f)
        })
      } else {
        if (this.validator.fields.find({ name: field.name })) {
          this.validator.detach(field.name)
        }
      }
    }

    addErrors = (field: string, message: any) => {
      const { errors } = this.validator

      if (errors.has(field)) {
        errors.remove(field)
      }

      errors.add(field, message)

      if (this._isMounted) {
        this.setState({ errors })
      }
    }

    render() {
      return <Component {...this.props}
                        validator={this.validator}
                        validate={this.validate}
                        attachRules={this.attachRules}
                        detachRules={this.detachRules}
                        errors={this.state.errors}
                        addErrors={this.addErrors}
                        clearErrors={this.clearErrors}/>
    }
  }

  withValidator.displayName = `withValidator_${Component.displayName || Component.name}`

  return withValidator
}

then use this hoc as following

class Page extends React.Component<*, State> {
  static displayName = 'Login Page'

  state = {
    form: {
      username: null,
      password: null,
    },
  }

  handleChange = async (name: string, value: any) => {
    const isValid = await this.props.validateOne(name, value)
    
    console.log(this.props.errors)
  }

  handleSubmit = async (evt) => {
    evt.preventDefault()

    const isValid = await this.props.validateAll(this.state.form)

    console.log(this.props.errors)
  }

  render() {
    console.log(this.props)
  }
}

export default withValidator(Page, [
  {
    name: 'username',
    rules: 'required',
    alias: 'Username',
  },
  {
    name: 'password',
    rules: 'required',
    alias: 'Password',
  },
])

Available Validation Rules

ReeValidate comes with a bunch of validation rules out of the box and they are all localized and cover most validation needs:

after
alpha
alpha_dash
alpha_num
alpha_spaces
before
between
confirmed
credit_card
date_between
date_format
decimal
digits
dimensions
email
ext
image
included
integer
ip
is
is_not
length
max
max_value
mimes
min
min_value
excluded
numeric
regex
required
required_if
size
url

Compatability

This library uses ES6 Promises so be sure to provide a polyfill for it for the browsers that does not support it.

Credits

license MIT

ree-validate's People

Contributors

alirezamirsepassi avatar cappe avatar moeen-basra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

ree-validate's Issues

Regex Problem

Versions:

  • ReactJs: ^16.11.0
  • Ree-Validate: ^1.0.15

Description:

why I get error when I set regex like this
this.validator = new Validator({ avatar: '', phone_no: 'numeric|max:12', address: 'regex:^[a-zA-Z0-9\s\.\-\/,]+$', city: 'regex:^[a-zA-Z\s]+$', postcode: 'numeric', state: 'regex:^[a-zA-Z\s]+$', country: 'regex:^[a-zA-Z\s]+$' })
this is example of test string on that regex https://regex101.com/r/tvUtu0/1

Error Occured :-

  1. Uncaught SyntaxError: Invalid flags supplied to RegExp constructor ']+$' ( IF I PUT REGEX ON COMMA )
  2. The address field format is invalid. ( IF I PUT REGEX ^ ...... + $ )

missing "same" rule

Versions:

  • ReactJs: 16.4.0
  • Ree-Validate: 3.0.2

Description:

same:field
The given field must match the field under validation.

Steps To Reproduce:

Error: [ree-validate] No such validator 'same' exists.

I need compare password and confirm password

ReeValidate.Validator is not a constructor

Versions:

  • ReactJs: 16.10.2
  • Ree-Validate: 3.3.0
  • webpack: 4.41.2

Description:

Uncaught TypeError: ree_validate__WEBPACK_IMPORTED_MODULE_16__.default.Validator is not a constructor

Steps To Reproduce:

this is step I use it:

import ReeValidate from 'ree-validate';
this.validator = new ReeValidate.Validator({
company_nm: 'required',
company_ab_nm: 'required',
zipcode: 'required',
address1: 'required',
TEL: 'required',
FAX: 'required',
})
And sometime when I install this library, there are some files is missing in dist folder.

multiple field attach

Versions:

  • ReactJs: 16.13.1
  • Ree-Validate:3.3.1

Description:

How can i attach multiple field at ones

const field = {
    name: 'fieldName',
    alias: 'Field Name',
    rules: 'rules'
}

this.validator.attach(field)

or is there any way to add alias here

this.validator = new ReeValidate.Validator({
            first_name: 'required|min:3',
})

validateAll triggers all error messages in form

Versions:

  • ReactJs: #.#.#
  • Ree-Validate:

Description:

Checking for validation with validateAll triggers all error messages, I just need to check the form validity without triggering the error messages.
Also flags like touched, dirty isn't changing in this.validator object.

Steps To Reproduce:

just use function
this.validate.validateAll(formdata).then(valid => console.log(valid));

How can we add message to one rule with more validation

Versions:

  • ReactJs: #.#.#
  • Ree-Validate:

Description:

Like i have below rules:
this.validator.attach({
name: "mobile_no",
alias: "Mobile Number",
rules: "required|numeric|length:10"
});

I want to display custom message for number and length validation.

Please tell me how to do this.

Required_if does not exist ?

Versions:

  • ReactJs: 16.0.1
  • Ree-Validate: 3.0.2

Description:

In your documentation, required_if is available . but when I check deeply in file . There is no required_if exists.

Steps To Reproduce:

Cant set alias for names

Versions:

  • ReactJs: #.#.#
  • Ree-Validate:

Description:

for a field called creditTypeOrDuration, i want to show "credit type or duration" to user.

Steps To Reproduce:

Different behaviour in chrome and firefox

Versions:

  • ReactJs: ^16.6.0
  • Ree-Validate:github:moeen-basra/ree-validate#development

Description:

we validate date using the following rule,

this.validator = new ReeValidate({
      from_date: 'date_format:DD/MM/YYYY|date_between:31/12/1899,' + moment().add('years', 1000).format("DD/MM/YYYY")
    })

The problem occurs because of date_between.
The above code is working perfectly in chrome, But when I use firefox browser it is not working correctly, it is always showing error,

We found the same related problem in vee-validate, [https://github.com/logaretm/vee-validate/issues/1027],
If you use the vee-validate plugin in our plugin then please solve this issue same as vee-validate(They update new version of vee-validate).

Thanks in advance

Add features like prestine, dirty, valid

This is the best react validation library similar to angular and vee-validate.
Can you please add feature like:
Form: valid, prestine, dirty etc
Fields: prestine, valid, dirty etc
Thanks

Versions:

  • VueJs: #.#.#
  • Vee-Validate:

Description:

Steps To Reproduce:

Version 3.3.0 update not working

Versions:

  • ReactJs: #.#.#
  • Ree-Validate: : ree-validate.esm.js does not exist

Description:

Version 3.3.0 not working after update from 3.0.2

Steps To Reproduce:

npm update ree-validate

How to validate object values

Versions:

  • ReactJs: #.#.#
  • Ree-Validate:

Description:

lets say we have an object
this.state = {
a : {
name: "",
age: ""
}
}

So i can validate on blur but when i try to trigger this.validate.validateAll() it will miss those inside the objects.

Steps To Reproduce:

Validating Dynamically added elements

Versions:

  • ReactJs: latest
  • Ree-Validate: latest

Description:

Currently i have an array of exams such as -

examName - examScore - Add/Delete

One can add more exams to the list along with thier score and remove or add them and i need to validate them. Right now we need to initialize the bag so i can't validate them dynamically.
Is there any alternative to this?

How to pass options parameters?

Hello!, I need translate the errors messages. I reed the vee-validate documentation but I don't know how to set up the options object here.

Thanks!

Custom Validation Rule and Passing Constructor Options

Versions:

  • ReactJs: #.#.#
  • Ree-Validate:

Description:

When using the extending options, give option for accessing the constructor option such as this.

  getMessage: field => "Email is already registered",
  validate: value => {
    this.customFunction('')
    return true;
  }
});```

### Steps To Reproduce:
For example running graqhql query in custom validation

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.