Eric Evans Eric Evans - 4 years ago 293
React JSX Question

How to validate jsx react

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download