question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Validation not working in functional component with hooks

See original GitHub issue

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>
  );
}

Issue Analytics

  • State:open
  • Created 4 years ago
  • Reactions:1
  • Comments:26 (3 by maintainers)

github_iconTop GitHub Comments

10reactions
stuyamcommented, Sep 19, 2019

If you can use forceUpdate with hooks like that then you can initialize the SRV with forceUpdate so it will do it automatically. something like this:

const [, forceUpdate] = useState()
const simpleValidator = useRef(new SimpleReactValidator({autoForceUpdate: {forceUpdate: forceUpdate}))

submitForm() => {
  const formValid = simpleValidator.current.allValid()
  if (!formValid) {
    simpleValidator.current.showMessages()
  }
}
9reactions
wztech0192commented, Oct 18, 2020

Here is a more advance custom hook to force rerender the component. This hook will not recreate a SimpleReactValidator instance in each rerender, tiny performance boost~

//useSimpleReactValidator.js
export default function useSimpleReactValidator(passInOptions = {}) {
    const [{ options }, forceUpdate] = React.useReducer(({ options }) => ({ options }), {
        options: passInOptions,
    });
    const simpleValidator = React.useMemo(
        () =>
            new SimpleReactValidator(
                options.autoForceUpdate
                    ? {
                          ...options,
                          autoForceUpdate: {
                              forceUpdate,
                          },
                      }
                    : options
            ),
        [options]
    );
    return [simpleValidator, forceUpdate];
}

//example
const [validator, forceUpdate] = useSimpleReactValidator({...anyOtherOptions, autoForceUpdate: true});
Read more comments on GitHub >

github_iconTop Results From Across the Web

react-simple-validator Validation not working in functional ...
I am trying to use is in the functional component using React Hooks but its now showing up the validation message on UI....
Read more >
Form Validation in React.js using React Functional ...
js tutorial will get you started with Forms in React.js by building a simple form and and showing how to perform validations on...
Read more >
How To Create and Validate a React Form With Hooks - Telerik
First, we import the field validators we created previously. After the imports, we have the touchErrors function. It basically loops through the ...
Read more >
Form Validator / React functional component - Syncfusion
This article provides a step-by-step instructions on using the React functional Hooks in a simple HTML form with the FormValidator component.
Read more >
Form validation with React Hooks WITHOUT a library
In our handleSubmit function, we now need to add the logic for validating our keys. I'm not too fond of forms that validate...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found