如果电话号码无效,我想显示“无效电话号码”错误信息,但如果电子邮件无效,我想显示“无效的电子邮件地址”。如果两者都错了,则同时显示两条错误消息。我需要return null,因为如果出现错误,我希望函数中断。问题是,现在它显示了每种情况下的两条错误消息。
constructor(props) {
super(props);
this.state = {
name: '',
email: '',
phone: '',
loading: false,
showError: false
};
}
if (!this.state.phone.match(numbers) || !this.state.email.match(regEx)) {
this.setState({ showError: true }, () => {
setTimeout(() => this.setState({ showError: false }), 2000);
});
return null;
}
<label htmlFor="phone">
PHONE{' '}
{this.state.showError && (
<span style={{ color: 'red' }}>Invalid phone number.</span>
)}
</label>
<label htmlFor="email">
EMAIL{' '}
{this.state.showError && (
<span style={{ color: 'red' }}>Invalid email address.</span>
)}
</label>发布于 2020-05-08 07:59:15
if (!this.state.phone.match(numbers)) {
this.setState({ showPhoneError: true }, () => {
setTimeout(() => this.setState({ showPhoneError: false }), 2000);
});
}
if (!this.state.email.match(regEx)) {
this.setState({ showEmailError: true }, () => {
setTimeout(() => this.setState({ showEmailError: false }), 2000);
});
}
if (!this.state.email.match(regEx) || !this.state.phone.match(numbers)) {
return null;
}我把它修正成这样,虽然我认为这不是最好的做法。
发布于 2020-05-08 05:44:01
var validation = `${
! name
? //error message here
:! phone
? //error message here
: phone.length < 2 // length
? //error message here
: !email
? //error message here
: email && !CheckEmail(email)
? //error message here
: true
}`;
if (validation === 'true') {
// api call or else
} else {
this.setState({showError:validation});
}发布于 2020-05-08 07:16:23
请尝试这样处理每个元素的错误。我还没有试过这段代码,但它可能对你有帮助。
constructor(props) {
super(props);
this.state = {
name: '',
email: '',
phone: '',
loading: false,
showErrors:{},
};
}
//This way you can handle error for phone uniquely
!this.state.phone.match(numbers)?
this.setState({showErrors:{...this.state.showErrors, phone:true}})
:
this.setState({showErrors:{...this.state.showErrors, phone:false}})
//This is for email
!this.state.email.match(regEx)?
this.setState({showErrors:{...this.state.showErrors, email:true}})
:
this.setState({showErrors:{...this.state.showErrors, email:false}})
<label htmlFor="phone">
PHONE{' '}
{this.state.showErrors.phone && (
<span style={{ color: 'red' }}>Invalid phone number.</span>
)}
</label>
<label htmlFor="email">
EMAIL{' '}
{this.state.showErrors.email && (
<span style={{ color: 'red' }}>Invalid email address.</span>
)}
</label>https://stackoverflow.com/questions/61672695
复制相似问题