Reputation: 160
I have a simple setup for validating a few form entries. It only pushes validation for the first entry. So in state I have:
this.state = {
username: '',
email: '',
zip: '',
errors:[]
}
The submit
button:
<div>
<button onClick={this.handleSubmit}
>submit
</button>
</div>
The submit button and the form both trigger handleSubmit
:
handleSubmit(e) {
e.preventDefault();
this.setState({errors:[]});
const {username, email, zip} = this.state;
const errors = validate(username, email, zip);
if (errors.length>0) {
this.setState({errors});
}
}
which hits validate
:
function validate(username, email, zip) {
let validEmail = RegExp(/[^@ \t\r\n]+@[^@ \t\r\n]+\.[^@ \t\r\n]+/);
let validZip = RegExp(/^\d{5}$/);
const errors = [];
if (username.length < 3 || null) {
errors.push('Name must be at least 3 characters long.');
}
if (validEmail.test(email)) {
errors.push('Email address must be valid email address.');
}
if (validZip.test(zip)) {
errors.push('Zip code must be 5 digits.')
}
console.log(errors);
return errors;
}
and then, from the updated state, errors are supposed to print as line items in:
<ul className="errorList">
{this.state.errors.map(
(error =>
<li key={error}>
{error}
</li>
)
)}
</ul>
but only the first validation is working (for username
), in a console log and in the unordered list.
Looking for advice ^~^
Upvotes: 0
Views: 540
Reputation: 36
validEmail.test(email)
return false
, try !validEmail.test(email)
will return true
if email failed
Upvotes: 2