问题
In React, I'm looking to add email validation (checks for @ and .com) to a form that currently checks for empty input fields.
I found this that does the job but can't figure out how to connect it to onSubmit along w/ my other validation.
Here's the link to this project's codepen for complete code.
Setting initial State for inputs and errors:
constructor() {
super();
this.state = {
inputs: {
name: '',
email: '',
message: '',
},
errors: {
name: false,
email: false,
message: false,
},
};
}
JS Handling Input, onBlur
updateInput = e => {
this.setState({
inputs: {
...this.state.inputs,
[e.target.name]: e.target.value,
},
errors: {
...this.state.errors,
[e.target.name]: false,
},
});
};
handleOnBlur = e => {
const { inputs } = this.state;
if (inputs[e.target.name].length === 0) {
this.setState({
errors: {
...this.state.errors,
[e.target.name]: true,
},
});
}
};
回答1:
Without refactoring too much of your code, we can just update the updateInput()
function to this:
updateInput = event => {
const { name, value } = event.target;
if (name === "email") {
this.setState({
inputs: {
...this.state.inputs,
[name]: value
},
errors: {
...this.state.errors,
email:
value.includes("@") &&
value.slice(-4).includes(".com")
? false
: true
}
});
} else {
this.setState({
inputs: {
...this.state.inputs,
[name]: value
},
errors: {
...this.state.errors,
[name]: false
}
});
}
};
Also see sandbox: https://codesandbox.io/s/conditional-display-input-errors-vfmh5
回答2:
one possible way is to add a conditioning to your code like so
if((e.target.name === "email") && !this.validateEmail(inputs[e.target.name]) && (inputs[e.target.name].length !== 0 ) ){
this.setState({
errors: {
...this.state.errors,
[e.target.name]: true,
},
});
}
so after generally you will have something like this that add the validate function
validateEmail (email) {
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return re.test(email)
}
then your unblur function will look like this
handleOnBlur = e => {
const { inputs } = this.state;
if (inputs[e.target.name].length === 0) {
this.setState({
errors: {
...this.state.errors,
[e.target.name]: true,
},
});
}
if((e.target.name === "email") && !this.validateEmail(inputs[e.target.name]) && (inputs[e.target.name].length !== 0 ) ){
this.setState({
errors: {
...this.state.errors,
[e.target.name]: true,
},
});
}
};
来源:https://stackoverflow.com/questions/56676342/react-adding-email-validation-to-empty-input-validation