Giter Club home page Giter Club logo

simple-react-validator's Introduction

Simple React Validator

A simple react and react native form validator inspired by Laravel validation.

View on NPM »

Powered by Dockwa

About

Simple React Validator is exactly as it sounds. We wanted to build a validator for react that had minimal configuration and felt natural to use. It's configuration and usage is similar to the Laravel PHP framework and make validation as easy as one line.

Working Example

Documentation

  1. Usage
  2. Setup
    1. Public Methods
    2. onBlur
    3. Conditional Fields
    4. React SFC's and Hooks
    5. React Native
  3. Rules
  4. Options
    1. Element
    2. Class Name
    3. Messages
    4. Validators
    5. Auto Force Update
    6. Localization
  5. Custom Validators

Usage

Open the example/index.html file for more usage examples of the library or check out the Example

npm

npm install simple-react-validator --save

bower

bower install simple-react-validator --save

3 Easy Steps

  1. Import and Initialize the validator.
import SimpleReactValidator from 'simple-react-validator';

es5

componentWillMount: function() {
  this.validator = new SimpleReactValidator();
},

es6

constructor() {
  this.validator = new SimpleReactValidator();
}
  1. Add validation rules under inputs. The message method accepts 5 arguments:
  • Field Name: A unique underscored string that gets replaced in the messaging as the name of the field.
  • Value: Usually the state of the current field.
  • Rules String: A pipe separated list of rules to apply to the string.
  • Options (Optional): Object of options same as the default options.
this.validator.message('title', this.state.title, 'required|email')

Example:

render() {
  return (
    <div className="container">
      <h1>Write a Review</h1>
      <div className="form-group">
        <label>Title</label>
        <input className="form-control" value={this.state.title} onChange={this.setTitle} />

        {/**********   This is where the magic happens     ***********/}
        {this.validator.message('title', this.state.title, 'required|alpha')}

      </div>
      <div className="form-group">
        <label>Email</label>
        <input className="form-control" value={this.state.email} onChange={this.setEmail} />

        {/**********   This is where the magic happens     ***********/}
        {this.validator.message('email', this.state.email, 'required|email', { className: 'text-danger' })}

      </div>
      <div className="form-group">
        <label>Review</label>
        <textarea className="form-control" value={this.state.review} onChange={this.setReview} />

        {/**********   This is where the magic happens     ***********/}
        {this.validator.message('review', this.state.review, 'required|min:20|max:120')}

      </div>
      <button className="btn btn-primary" onClick={this.submitForm}>Save Review</button>
    </div>
  );
}
  1. Check if the validation passes when submitting and turn on messaging if it fails. Once messaging is turned on, validation messages will change and update as the user types.
submitForm() {
  if (this.validator.allValid()) {
    alert('You submitted the form and stuff!');
  } else {
    this.validator.showMessages();
    // rerender to show messages for the first time
    // you can use the autoForceUpdate option to do this automatically`
    this.forceUpdate();
  }
}

There is another method you can use to check if a single field is valid or not.

if (this.validator.fieldValid('email')) {
  // booya this field is valid!
}

Note: autoForceUpdate

As of v1.1.0 you can initialize the the constructor with the autoForceUpdate option and pass it react instance that is responsible for the state. This will automatically call the this.forceUpdate() for you when showMessages, hideMessages, showMessageFor, and hideMessageFor are called.

constructor() {
  this.validator = new SimpleReactValidator({autoForceUpdate: this});
}

1. Available Public Methods

getErrorMessages() Returns a JS object, key being the field name, value being the error message.

showMessages() Turns on showing messages for all messages.

hideMessages() Turns off showing messages for all messages.

showMessageFor(field) Turns on showing messages for a specific field. Useful for onBlur.

hideMessageFor(field) Turns off showing messages for a specific field. Useful for onBlur.

allValid() Returns a boolean if all the fields pass validation or not.

fieldValid(field) Checks if a single field is valid or not.

purgeFields() Empties the validation object for conditional fields.

messageWhenPresent(message, options = {}) Show a message when the message is set, good for ajax validation errors.

check(value, validations) A simple way of checking a value against a built in validation rule. Does not add to the validator, just gives a true / false return value.

message(field, value, validations, options = {}) How you define validation rules and add messages into the form.

2. onBlur

You can use the react onBlur action to show individual fields once the input is blurred. Use the showMesssageFor or hideMessageFor methods.

<div>
  <label>Email</label>
  <input value={this.state.email} onChange={/* update email */} onBlur={() => this.validator.showMessageFor('email')} />
  {this.validator.message('email', this.state.email, 'required|email')}
</div>

3. Conditional Fields

A field is added to validator via the above message method. But sometimes you want to conditionally add and remove validation as the form is completed. For this you can use the purgeFields method to clear all validator before each render so only the fields added during that render are validated.

render() {
  this.validator.purgeFields();
  return (
    <div>
      <div className="form-group">
        <label>Address Line 1</label>
        <input className="form-control" value={this.state.title} onChange={this.setTitle} />
        {this.validator.message('title', this.state.title, 'required|alpha')}
      </div>
      {this.optinallyAddAnotherAddressLine()}
      <button className="btn btn-primary" onClick={this.submitForm}>Save Review</button>
    </div>
  );
}

4. React Hooks

SimpleReactValidator is a class but if you instantiate a class in a stateless React component it will do this on every render (losing any message information that may have been added).

useRef: instruct React to treat SimpleReactValidator as a singleton:

const simpleValidator = useRef(new SimpleReactValidator())

<Input
  name="name"
  value={companyInformation.name}
  onChange={handleInputChange}
  onBlur={()=>simpleValidator.current.showMessageFor('name')} />
{simpleValidator.current.message('name', companyInformation.name, 'required')}

For more detail see issue: #97

5. React Native

You need to wrap validator with <Text> Element.

<Text>
  {this.validator.message('title', this.state.title, 'required|alpha')}
</Text>

Rules

This is the list of all the rules you can validate form inputs against. When using multiple rules, separate them with a pipe |. When adding options, append a colon to the rule and separate options with commas. Examples: 'required|min:20|max:120' and 'required|in:stu,stuart,stuyam'. You can apply the rules via an array like ['required', {max: 20}, {min: 120}] or ['required', {in: ['stu', 'stuyam']}]. This is necessary for things like the regex validator where you may be using pipes or commas in the regex and would conflict with the rule string.

accepted

Must be a JavaScript true, good for required check boxes.

after:date

Must be after date. See Date for info on accepted date values.

after_or_equal:date

Must be after or on date. See Date for info on accepted date values.

alpha

Must only container letters.

alpha_space

Must only container letters and spaces.

alpha_num

Must only container letters and numbers.

alpha_num_space

Must only container letters, numbers, and spaces.

alpha_num_dash

Must only container letters, numbers, dashes, and underscores.

alpha_num_dash_space

Must only container letters, numbers, dashes, underscores, and spaces.

array

Must be a JavaScript Array.

before:date

Must be before date. See Date for info on accepted date values.

before_or_equal:date

Must be before or on date. See Date for info on accepted date values.

between:min,max,type(optional)

Must be between two values. See Size for info on how size is calculated and how options work.

boolean

Must be a JavaScript Boolean.

card_exp

Must be a valid credit card expiration date. Ex. 10/18 or 10/2018

card_num

Must be a valid credit card number. Ex. 4242424242424242 or 4242 4242 4242 4242

currency

Must be a valid currency. Currency symbols ($, £, €, ¥) and commas are optional. Ex. 4.25, $3000 or £3,245,525.12

date

Must be a date type momentjs date. Requires Momentjs

date_equals:date

Must be a date on a specific date.
Options: date must be a momentjs date object.

email

Must be a valid email format.

in:foo,bar,...

Must match a string in options.
Options: list of values it must match.

integer

Must be an integer value.

max:size,type(optional)

Must not be greater than max. See Size for info on how size is calculated and how options work.

min:size,type(optional)

Must not be less than min. See Size for info on how size is calculated and how options work.

not_in:foo,bar,...

Must NOT match a string in options.
Options: list of values it must not match.

not_regex:pattern

Must NOT match a regex.
Options: regex it must not match.
Note: if your regex uses a | or , or other special characters use the array syntax to define the rule.

numeric

Must be a number of any type.
Positive numbers: "numeric|min:0,num"
Negative numbers "numeric|max:0,num"

phone

Must be a valid phone number format. Ex. (508) 555-1234 or 5085551234

regex:pattern

Must match a regex.
Options: regex it must match.
Note: if your regex uses a | or , or other special characters use the array syntax to define the rule.

required

Must be present, use with other validators to require them.

size:size,type(optional)

Must be of a particular size. Can be a string length, array length, or number.
Options: type is optional and defaults to string. There are 3 types 'string', 'num', and 'array'. String is length of string, num is size of number, array is length of array.

string

Must be of type string.

typeof:type

Must be of JavaScript type specified in the options.
Options: compare the type of the value given to the type provided. Use array syntax to define the type else it will always be type string.

url

Must be a valid url. Ex. https://dockwa.com or dockwa.com

Options

The Simple React Validator can receive an options object when initialized or as the fourth parameter when defining a validator. There are 4 options you can provide.

1. element:

Accepts a block where you can return the default element that you want to wrap the message from a validator message. The default element is <div className="srv-validation-message">{message}</div>. If you are using React Native the default will be just the message the gets returned. You can also set element: false to just return a message.

  • Takes 2 params
  • message: The message coming from the validator.
  • className (optional): Will optionally be provided so you can change the className on a per validation basis.
this.validator = new SimpleReactValidator({
  element: message => <div>{message}</div>
  // OR
  element: (message, className) => <div className={className}>{message}</div>
})

2. className:

String of classes to be passed into an element, default is srv-validation-message and can be overriden.

3. messages:

Accepts an object to override validation messages. It also accepts a default which will override all messages.

this.validator = new SimpleReactValidator({
  messages: {
    email: 'That is not an email.'
    // OR
    default: 'Validation has failed!'  // will override all messages
  },
})

4. validators:

Accepts an object of custom validators. See Custom Validators for more info on defining custom validators.

5. autoForceUpdate:

Accepts a react instance and will automatically be called when messages are shown and hidden automatically. More on autoForceUpdate

6. locale:

Accepts a string with the localized messages of your choice. For this to work, the correct language file also needs to be loaded into your front end. Current Supported Languages. To contribute to translating the project use this file as a template.

// sets french default validation messages.
this.validator = new SimpleReactValidator({locale: 'fr'});

You can apply custom messages with the messages option. However you can also apply a custom language that you can later select with the addLocale class method.

SimpleReactValidator.addLocale('klingon', {
  accepted: 'Hab SoSlI’ Quch!',
  email: 'Heghlu’meH QaQ jajvam'
});
...
this.validator = new SimpleReactValidator({locale: 'klingon'});

Custom Validators

You can write custom rules that you can use the validate. A rule has 4 options:

  1. message: The message the will be shown when the validation fails. :attribute will be replaced by the humanized name that your provide of the attribute you are validating (supports snake_case or camelCase).
  2. rule: Accepts a block that returns true if validator passes and false if it fails.
  • Takes 3 params
  • val: The value that is being validated.
  • params: An array containing the params passed into the validator.
  • validator: The validator object, allows you to access helper methods such as validator.helpers.textRegex(val, regex) which returns true or false if the regex passes.
  1. messageReplace (optional): Accepts a block uses to modify and return the message on the fly.
  • Takes 2 params
  • message: The message provided above.
  • params: An array containing the params passed into the validator.
  1. required (optional): True if you want the validator to be implicitly required when it is applied. All validators are not required by default. The equivalent of adding required to each validation definition.

Example:

constructor() {
  this.validator = new SimpleReactValidator({
    validators: {
      ip: {  // name the rule
        message: 'The :attribute must be a valid IP address and must be :values.',
        rule: (val, params, validator) => {
          return validator.helpers.testRegex(val,/^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/i) && params.indexOf(val) === -1
        },
        messageReplace: (message, params) => message.replace(':values', this.helpers.toSentence(params)),  // optional
        required: true  // optional
      }
    }
  });
}

Usage:

render: function() {
  return (
    <div className="container">
      <h1>Give Me Your IP</h1>
      <div className="form-group">
        <label>IP Address</label>
        <input className="form-control" value={this.state.ip} onChange={this.setIP} />
        {this.validator.message('ipAddress', this.state.ip, 'required|ip:127.0.0.1')}
      </div>
      ...
    </div>
  );
},

simple-react-validator's People

Contributors

bisark avatar cso86 avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar e-gauthier avatar egomaw avatar ej2015 avatar fabricio-agnesm avatar frankyso avatar garethfentimen avatar haqim007 avatar iamgideonidoko avatar jamiekcarson avatar joestandring avatar karankhirsariya avatar kindslayer avatar leonskrilec avatar lukkoro avatar mahshadalishahi avatar maya313 avatar oguzhanozpinar avatar oniice avatar pdpol avatar prince17dec avatar rek avatar rubenkuipers avatar skout90 avatar stuyam avatar wztech0192 avatar

Stargazers

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

Watchers

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

simple-react-validator's Issues

Hi, Two questions

  1. How do I clear error messages after I submit? After I submit, I tried to clear all the fields, but suddenly all required error messages show up.
  2. How do I set an optional field? In my case, check the phone number if the user fills it, but it's not required.

Validation not working in functional component with hooks

I am trying to use is in the functional component using React Hooks but its now showing up the validation message on UI

My React version is below
"react": "^16.8.6",
"react-dom": "^16.8.6",

Below is my code, Please check if I am missing anything.

import React from "react";
import SimpleReactValidator from "simple-react-validator";

export default function ExampleForm (){
  const [values, setValues] = React.useState({
    title: 'There was a server error the prevented the form from submitting.',
    email:'',
    review:''
  });

  const  handleChange = name => event => {
    setValues({ ...values, [name]: event.target.value });
  };

  const validator = new SimpleReactValidator({
    className: 'text-danger',
    messages: {
      email: 'That is not an email.',
    },
    validators: {
      ip: {
        message: 'The :attribute must be a valid IP address.',
        rule: function(val, params, validator) { 
          return validator.helpers.testRegex(val,/^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/i) && params.indexOf(val) === -1
        }
      }
    }
  });

  const submitForm= ()=> {
    if (validator.allValid()) {
      alert('You submitted the form and stuff!');
    } else {
      validator.showMessages();
    }
  }

  return (
    <div className="container">
      <div className="form-group">
        <label>Title</label>
        <input className="form-control" value={values.title}  onChange={handleChange("title")} />
 
        {/**********   This is where the magic happens     ***********/}
        {validator.message('title', values.title, 'required|alpha')}
 
      </div>
      <div className="form-group">
        <label>Email</label>
        <input className="form-control" value={values.email} onChange={handleChange("email")} />
 
        {/**********   This is where the magic happens     ***********/}
        {validator.message('email', values.email, 'required|email')}
 
      </div>
      <div className="form-group">
        <label>Review</label>
        <textarea className="form-control" value={values.review} onChange={handleChange("review")} />
 
        {/**********   This is where the magic happens     ***********/}
        {validator.message('review', values.review, 'required|min:20|max:120')}
 
      </div>
      <button className="btn btn-primary" onClick={submitForm.bind(this)}>Save Review</button>
    </div>
  );
}

Dynamic validation [feature]

At the moment, there doesn't seem a nice way to do dynamic validation. It's much more convenient to call "allvalid()" instead of performing validation one by one.

I have a scenario where user has a drop down. Validation for the drop down field should only be applied if the drop down value is equal to a specific value, otherwise this field should not be validated.

Could you please let me know an elegant way to handle this with your library?

This is my proposed solution (new parameter 'disabled'):

image

autoForceUpdate type issue

Hi,

The type of autoForceUpdate is defined as a boolean as:
interface IOptions { messages?: any; className?: any; autoForceUpdate?: boolean; element?: any; locale?: string; }
but the documentation states it should get the component instance 'this'.
Hence, it gives an error here:
forceUpdateIfNeeded: function () { this.parent.autoForceUpdate && this.parent.autoForceUpdate.forceUpdate(); },

The error is:
this.parent.autoForceUpdate.forceUpdate is not a function

Please have a look. I think the type of the prop should be modified.

Validation doesn't work when last field is pre-populated

Hi,

I'm running into a strange issue while using your validator. I have a form with a bunch of fields that a registered user can use to edit their profile, all marked as required (which is the only validation rule in place). I am pre-filling the fields with the current user's info, but a few of them may be blank if the user never entered certain details.

The weird thing happening is that, if the last field in the form is pre-filled, validation doesn't work: all values are posted on form submit, including the required ones even though they're blank (an empty string is posted in their case).

Here's my code:

export default class UserProfile extends React.Component {

	static contextType = AppContext	

	static async getInitialProps( { req } ) {

		const userProfile = await asyncReq( userProfileEP( req.userID ) )

		return { userProfile }
	
	}	

	constructor( props ) {
		
		super( props ); 

		const { userProfile } = this.props
	
		this.state = {
			fields: {
				rcp_user_first: userProfile.firstName,
				rcp_user_last: userProfile.lastName,
				rcp_country: userProfile.country,
				rcp_city: userProfile.city,
				rcp_postal_address: userProfile.postalAddress
			}
		}	

		this.handleInputChange = this.handleInputChange.bind( this )
		this.handleSubmitForm = this.handleSubmitForm.bind( this )	

		this.validator = new SimpleReactValidator()		
	
	}

	handleInputChange(e) {
	    
	    const target = e.target
	    const value = target.value
	    const name = target.name

        this.setState( prevState => ({
        	...prevState,
            fields: {
            	...prevState.fields, 
	      		[name]: value,
            }
        }))         	    

	}		

	async handleSubmitForm(e) {

		e.preventDefault()

		if( this.validator.allValid() ) {

			console.log( 'Submitted values', this.state.fields );

		} else {

			this.validator.showMessages()
			this.forceUpdate()

		}

	}

	render() {		

		const { rcp_user_first, rcp_user_last } = this.state.fields
		const { rcp_country, rcp_city, rcp_zip_code, rcp_postal_address } = this.state.fields

		const page = 
			<Layout>
				<PageHeader title="Edit your profile" /> 
				<PageContent>
					<SingleColumn>
						<form>
							<HasField 
								label="Your first name"
								validationErrors={ 
									this.validator.message( '', rcp_user_first, "required" ) 
								}
							>
								<input
									name="rcp_user_first"
									placeholder="Please enter your first name..."
									type="text"
									value={ rcp_user_first } 
									onChange={ this.handleInputChange }							
								/>
							</HasField>
							<HasField 
								label="Your last name"
								validationErrors={ 
									this.validator.message( '', rcp_user_last, "required" ) 
								}
							>
								<input
									name="rcp_user_last"
									placeholder="Please enter your last name..."
									type="text"
									value={ rcp_user_last } 
									onChange={ this.handleInputChange }							
								/>
							</HasField>	
							<HasField 
								label="Your country"
								validationErrors={ 
									this.validator.message( '', rcp_country, "required" ) 
								}
							>
								<input
									name="rcp_country"
									placeholder="Please choose a country..."
									type="text"
									value={ rcp_country } 
									onChange={ this.handleInputChange }							
								/>
							</HasField>	
							<HasField 
								label="Your city"
								validationErrors={ 
									this.validator.message( '', rcp_city, "required" ) 
								}
							>
								<input
									name="rcp_city"
									placeholder="Please enter a city..."
									type="text"
									value={ rcp_city } 
									onChange={ this.handleInputChange }							
								/>
							</HasField>	
							<HasField 
								label="Your postal address"
								validationErrors={ 
									this.validator.message( '', rcp_postal_address, "required" ) 
								}
							>
								<input
									name="rcp_postal_address"
									placeholder="Please enter your postal address..."
									type="text"
									value={ rcp_postal_address } 
									onChange={ this.handleInputChange }							
								/>
							</HasField>																																																																									                						
							<Btn
								btnLabel="Update your profile"
								onBtnClick={ this.handleSubmitForm }
							/>
						</form> 
					</SingleColumn>
				</PageContent>			
		    </Layout>
		
		return checkAuth( this.context.state.user.ID, page )
	
	}	

}

If the last filed ("Postal address") is not pre-populated, everything works as it should; if it is, the form is submitted as if all fields were valid...

How can set a custom message for a field?

Im already use your example code to set my message on spanish:
this.validator = new SimpleReactValidator({
messages: {
email: 'That is not an email.'
// OR
default: 'Validation has failed!' // will override all messages
},
}

but Im still getting the message on english, , here's my code:

constructor(props) {
    super(props);
    this.state = {
      name: '',
    };

   this.validator = new Validator({
      element: message => (
        <span style={error}>
          <i className="fa fa-exclamation-circle" aria-hidden="true" />
          { ` ${message}`}
        </span>
      ),
      messages: {
        name: 'El campo nombre es requerido',
      },
    });

<div className="form-group">
 <label htmlFor="name">Nombre: *</label>
 <input
 type="text"
 name="name"
 onChange={this.onChangeHandle}
 className="form-control"
 id="name"
 placeholder="Nombre Campaña / Cupón"
 />
 {this.validator.message('name', this.state.name, 'required|alpha')}
 </div>

Custom Rules not working

i used your code but

constructor(props){
        super(props);
        this.state = {
            firstname: "",
            lastname: "",
            mobile_no: "",
            email: "",
            password: "",
            city_id: "",
            preference_list: "",
            medium: "", //how did u find us
            is_looking_for: "",
            affiliate: "",
        
        };
this.validator = new SimpleReactValidator({
            ip: { //name the rule
              message: 'The :attribute must be a valid IP address.', //give a message that will display when there is an error. :attribute will be replaced by the name you supply in calling it.
              rule: function(val, options){ //return true if it is succeeds and false it if fails validation. the _testRegex method is available to give back a true/false for the regex and given value
                // check that it is a valid IP address and is not blacklisted
                this._testRegex(val,/^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/i) && options.indexOf(val) === -1
              }
            }
          });

    }

but gives me error

Uncaught TypeError: this._testRegex is not a function

Please let know whats wrong.
Thanks

Add support for camel cased names.

Currently we support:

{this.validator.message('tax_rate', this.state.taxRate, 'required|numeric')}

Would like to be able to support:

{this.validator.message('taxRate', this.state.taxRate, 'required|numeric')}

Custom validation rule with a promise

I am trying to verify by getting validation from back end, I have added a rule

this.validator = new SimpleReactValidator({
            element: message => message,
            validators: {
                hasAHouseNumber: {
                    message: 'The :attribute must contain a number.',
                    rule: function(val, params, validator) {
                        API.getInstance().getPlaceDetails(val)
                            .then(response => {
                                if (response.status === 200 && response.data.status === 'OK')
                                {
                                    console.log(response.data.result.address_components)
                                    response.data.result.address_components.some(item => {
                                        if (item.types.indexOf('street_number') > -1) {
                                            console.log('here')
                                            return true
                                        }
                                    })
                                }
                                return false
                            }).catch(error => {
                                console.log(error)
                                return false
                            })
                        // return false
                    }
                }
            }
        });

But validation rules do not seem to get the result from the promise, am I doing something wrong here ?

It's not working with redux actions?

Hello, plugin is not working with redux actions which trigging onChange?

i have an input:

<input name="name" value={this.props.form.name} required="required" onChange={event => this.props.getName(event.target.value) } />

and validator:
{this.validator.message('n', this.props.form.name, 'required|alpha')}

i wan't to show message at onChange but message not showing.
with interesting way validation working when at onClick submit button if i will call validAll method.

updated: it's worked when i added onBlur showMessageFor

How do i run validation on blur

Right now i can only trigger validation on start or on submit with this.validator.showMessages() but my form is really long and i want to trigger it on blur, please explain how can i do it or extend the current library.

Cannot use className

This only works if I remove the last param (the className)

{this.validator.message(
  "first_name_validation",
  this.state.first_name,
  "required",
  "text-danger"
)}

How I set the className correctly?

Can't validate MomentJS date object

"Date validators require using momentjs and moment objects."

The validation gives that error whenever I try to validate a YYYY-MM-DD date.

I am using an input type of "date" and convert the date to a MomentJS date object and it still gives this error.

I looked everywhere in the documentation that covers how to use MomentJS as well as the CodePen you provided but it doesn't cover dates.

It would be great if you can point me to the right direction and thanks for the help!

Email Validation

Hi,

An user reported that he couldn't signup due to an email validation issue.
His email was "[email protected]" so I've noticed the validator doesn't accept "_"
I've solved via custom validator but I find it relevant for devs to know.

Cheers

onBlur() validation message not showing up

Hi guys,
Thanks for implementing onBlur after installing version 1.1.0. I have trialled in one of my input boxes. When onBlur is triggered, your showMessageFor function is being called (why do we pass null into it?) with all the right inputs and the validation rules are being applied but no message is showing up in the browser. Below is the code (excerpts). Let me know if you need any further info.
Many thanks,
Katie

constructor(props) {
  super(props);
  this.handleQuestionChange = this.handleQuestionChange.bind(this);
  this.handleSubmit = this.handleSubmit.bind(this);
  this.validator = new SimpleReactValidator({
    autoForceUpdate: this,
    messages: {
      default: 'Validation has failed!',  // will override all messages
      meter: 'Invalid meter number: must be a 10 or 11 digit number'
    }
  });
}

<div className="col-md-4">
  <label>Meter Number</label>
  <input
    type="text"
    id="meterNumInput"
    name="meterNumInput"
    placeholder="enter a 10 or 11 digit meter number"
    onChange={this.handleMeterNumChange}
    onBlur={this.validator.showMessageFor.bind(null, 'meter')}
    className="form-control"
    value={this.state.meterNum}
  />
  <div className="small">
    {this.validator.message('meter number', this.state.meterNum, 'required|min:1000000000,num|max:99999999999,num')}
  </div>
</div>

Can not validate DatetimePickerTrigger using MomentJS

Hi, I have a problem to ask you:

I'm trying to validate Datetime picker using MomentJS but I don't know how does it work.

This is my code:
<DatetimePickerTrigger moment={this.state.moment} onChange={this.handleChange}> <input type="text" className="style-field-date" value={this.state.moment.format('YYYY-MM-DD HH:mm')} readOnly /> </DatetimePickerTrigger>

I tried { this.validator.message('date', this.state.moment && moment(this.state.moment, 'DD-MM-YYYY'), 'after:date') } but it didn't work.
Please help me validate this field.
Thanks you

Input file

How can I implement a validation with an input file?
I put it in required but when I attach a file I still get the required message ..

How to use

this.validator = new SimpleReactValidator()
but tip SimpleReactValidator is not defined

Differences between what fieldValid returns and message does

Nice, clean, simple library, thank you!

I noticed a discrepancy between what this.validator.message(...) and this.validator.fieldValid('fieldName') returns. Well, I realize they both return two different things, but they do not coincide. On first render, this.validator.message(...) doesn't render anything for a required field (as expected).

But this.validator.fieldValid('fieldName') returns false on a required field on first render. So my subcomponent that I pass isValid={this.validator.fieldValid('address')} to, is false, which renders an is-invalid CSS class, yet the this.validator.message returns nothing.

onBlur Event

Can you add an onBlur event to show error message to a certain field only?

Validation Problem

validation proper not working on the same page.

like login button for login tab and signup button for signup tab.
login tab validation fired on signup button and signup tab validation fired on login button.

Email validation issues
[email protected]
m..k.@yahoo...com
[email protected]

Change of language

Hello, is there any way to change the language? I was manually changing the messages ..

validation issue

I am try to add validation and i have added successfully and working nice but i have 5 fields in form and i have only last field filled and submit form so validation message not display and submit form with blank data.

i am using this.validator.allValid() function for validation please check my code.

`import React from 'react';
import { connect } from 'react-redux';
import { Row, Col, Form, Button } from 'react-bootstrap';
import moment from 'moment';
import SimpleReactValidator from 'simple-react-validator';
import { userActions } from '../../actions';
import { history } from '../../helpers';
import Header from '../../components/Header';
import '../../assest/style.css';

const style = {
rowPadding: {
padding: 10
},
formFieldMarginBottom: {
marginBottom: 5
},
Button: {
marginLeft: 5
}
}

class AddUser extends React.Component {
constructor(props){
super(props);
this.state = {
v_firstname: '',
v_lastname: '',
v_email: '',
password: '',
v_phone_number: '',
created_at: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
updated_at: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
}
this.validator = new SimpleReactValidator();
this.formSubmit = this.formSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}

handleChange(event){
    event.preventDefault();
    const name = event.target.name;
    const value = event.target.value;
    this.setState({
        [name]: value
    });
}

formSubmit(e){
    e.preventDefault();
    if (this.validator.allValid()) {
        this.props.dispatch(userActions.addUser(this.state));
        history.push('/users');
      } else {
        this.validator.showMessages();
        this.forceUpdate();
      }
}

render(){
    return(
        <div>
            <Header />
            <Row style={style.rowPadding}>
                <Col xs lg="12">
                    <h1>Add User</h1>
                    <Form onSubmit={this.formSubmit}>
                        <Form.Row style={style.formFieldMarginBottom}>
                            <Col xs lg="6">
                                <Form.Control type="text" name="v_firstname" placeholder="First name" value={this.state.v_firstname} onChange={this.handleChange} />
                                {this.validator.message('', this.state.v_firstname, 'required')}
                            </Col>
                        </Form.Row>
                        <Form.Row style={style.formFieldMarginBottom}>
                            <Col xs lg="6">
                                <Form.Control type="text" name="v_lastname" placeholder="Last name" value={this.state.v_lastname} onChange={this.handleChange}/>
                                {this.validator.message('', this.state.v_lastname, 'required')}
                            </Col>
                        </Form.Row>
                        <Form.Row style={style.formFieldMarginBottom}>
                            <Col xs lg="6">
                                <Form.Control type="email" name="v_email" placeholder="Email" value={this.state.v_email} onChange={this.handleChange}/>
                                {this.validator.message('', this.state.v_email, 'required|email')}
                            </Col>
                        </Form.Row>
                        <Form.Row style={style.formFieldMarginBottom}>
                            <Col xs lg="6">
                                <Form.Control type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handleChange}/>
                                {this.validator.message('', this.state.password, 'required')}
                            </Col>
                        </Form.Row>
                        <Form.Row style={style.formFieldMarginBottom}>
                            <Col xs lg="6">
                                <Form.Control type="text" name="v_phone_number" placeholder="Phone Number" value={this.state.v_phone_number} onChange={this.handleChange}/>
                                {this.validator.message('', this.state.v_phone_number, 'required')}
                            </Col>
                        </Form.Row>
                        <Button type="submit" variant="success">Save</Button>
                        {/* <Button style={style.Button} variant="danger">Cancel</Button> */}
                    </Form>
                </Col>
            </Row>
        </div>
    );
}

}

function mapStateToProps(state, ownProps) {
return {
users: state.users.users
}
}

const connectedAddUser = connect(mapStateToProps)(AddUser);
export { connectedAddUser as AddUser }; `

How to show single message?

I just want to show single message for example I have 3 fields (name, email, phone)

I want to show the message of a single field only if that field is already touched,

how can I achieved it?

Have you used it with Material UI 1.0.0?

It's not a issue but more of a question. Can you help me use this with material UI? I have used it with MI errors but it creates a

inside a

which gives an error. Can you help me with this.

<p class="MuiFormHelperText-root-69" id="name-helper-text">
    <div class="validation-message">The company name field is required.</div>
</p>

it does not work with typescrypt

I'm doing a web application with "create-react-app --typescript" but it throws the following error when including "simple-react-validator"
imagen
I think it's because the definitions file of typescript is missing, but it does not exist yet (npm install @ types / simple-react-validator does not find anything)

Is there a way to programmatically push validation messages.

I am trying to push server side validation messages to the fields.

For example is there a method that can be used to do this =>

errors.forEach(item => {
 this.validator.**push**(item.fieldname, item.message)
})

this.validator.showMessages()
this.forceUpdate()

I used push method as an example here.

Email verification makes the field required

Hi,

I have two fields in my form

  1. Email (required)
  2. Alternative Email (optional)

but when I use the 'email' validator in the alternate email field, without the required validator, it automatically makes the Alternative Email required.

In other words I want the Alternative Email to be blank.

val is not defined

I am using this amazing component in my application with TypeScript.
I applied required validator and it gives me this error as the component loads:


simple-react-validator.min.js:108 Uncaught ReferenceError: val is not defined
    at Object.isBlank (simple-react-validator.min.js:108)

On debugging, I found that this comes at this code segment:

    ``` isBlank: function (e) {
      return null == e || this.testRegex(val, /^[\s]*$/);
    }, ```

I searched for the variable val in the code but could not find it. it is undefined and causes this error. I guess it should be e rather than val as in all other methods such as:

          return e === Object(e) && Object.keys(e).length ? Object.keys(e)[0] : e.split(":")[0];
        },```

Validations are slow when using more than one custom validations

this.validator = new SimpleReactValidator({ messages:{ isDate:"Invalid Date Format" }, validators: { isDate: { rule: function(val, params, validator) { console.log("Validator:",val); return validator.helpers.testRegex(moment.isMoment(val) ? val.format("YYYY-MM-DD HH:mm:ss"):val ,/(?:(\d{4})([\-\/.])([0-3]?\d)\2([0-3]?\d)|([0-3]?\d)([\-\/.])([0-3]?\d)\6(\d{4}))(?:\s+([012]?\d)([:hap])([0-5]\d))?/i); } } } });

is This because of regex ? . Or is there any Fix for this issue ?. I've been facing this weird issue when i was started using more than one isDate validation on a Date picker .

Passing rules results

In simple-react-validator we can use allValid() method to validate all fields and fieldValid(field) to validate single field. We can only get boolean if value pass all rules or not.

So here is my question, is it possible to add method provide us which rules value doesn't pass? For every rule we could get boolean if input value pass it or not. For example if I have this field:

this.validator.message('email', this.state.email, ['required', 'email'])

and I want to know which rules my input pass I can call:

this.validator.passedRules('email') // [true, false]

It could be very useful to me and perhaps to other users. I would be grateful if You can take up my problem. Thank You for developing this helpful library.

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.