4

I"m trying to validate password field to show an alert when the validation fails

Here's what I've tried so far but it's not working. Any help is greatly appreciated.

class PasswordForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {value: ''};

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        this.setState({value: event.target.value});
    }

    validate(event) {
        var pass = event.target.value;
        var reg = '/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,32}$/';
        var test = reg.test(pass);
        if (test) {
            alert('pass');
        } else{
            alert('fail');
        }
    }

    handleSubmit(event) {
        if(this.state.value.length < 8) {
            return false;
        }

        alert('A password was submitted that was ' + this.state.value.length + '    characters long.');
        event.preventDefault();
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <label>
                    Password:&nbsp;
                    <input type="password" value={this.state.value} onChange={this.handleChange} onInput={this.validate}/>
                </label>
                <input type="submit" value="Submit" />
            </form>
        );
    }
}

ReactDOM.render(
    <PasswordForm />,
    document.getElementById('root')
);

What I want is when the user clicks on submit an alert box pops up if validation fails.

3
  • 1
    there is a good plugin for validation work npmjs.com/package/validator Commented Feb 6, 2017 at 5:36
  • Thanks but I would really like to know how to do it on my own. That's why it's just one field. Commented Feb 6, 2017 at 5:38
  • validate() method haven't been bound in constructor Commented Feb 6, 2017 at 5:41

3 Answers 3

3

Not sure about the regex you used, so used a simple one that will accept only upper case characters. You are already using the onChange method, so using a separate method for validation is not required, use this onChange method that will first check whether pass is valid or not then only set the state value:

 handleChange(event) {
       var pass = event.target.value;
       var reg = /^[A-Z]*$/;
       var test = reg.test(pass);
       if (test) {
          alert('pass');
          this.setState({value: pass});
       }else{
         alert('fail');
       }        
  }

Check this jsfiddle: https://jsfiddle.net/6q53prks/

Let me know if you need any help.

Sign up to request clarification or add additional context in comments.

1 Comment

@Hosar whats the error in that ? could you please specify which part is not working ? its working for me as i am expecting
1

maybe this https://codepen.io/dagman/pen/wgXRyZ

class PasswordForm extends React.Component {
    constructor(props) {
    super(props);

    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        this.setState({
            value: event.target.value
        });
    }

    handleSubmit(event) {
        event.preventDefault();

        const { value } = this.state;
        const re = new RegExp("^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,32}$");
        const isOk = re.test(value);

        console.log(isOk);

        if(!isOk) {
            return alert('weak!');
        }

        alert('A password was submitted that was ' + value.length + ' characters long.');
    }

     render() {
         return (
            <form onSubmit={this.handleSubmit}>
                <label>
                    Password:&nbsp;
                    <input type="password" value={this.state.value} onChange={this.handleChange} />
                </label>
                <input type="submit" value="Submit" />
            </form>
        );
    }
}

ReactDOM.render(
    <PasswordForm />,
    document.getElementById('root')
);

1 Comment

could you provide any input value that will not result into weak ?? because i used many but not getting success, i tried this also: Abcd#12345*12$QWER
0
 const passwordRegex =
            /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@*()_+\-=[\]{};':"\\|,.<>/?]).{8,}$/;
          var test = passwordRegex.test(e.target.value);
          setPasswordError(
            !test
              ? "password is not Strong"
              : e.target.value.length > 0
              ? ""
              : "password is required"
          );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.