当我点击发送按钮时,表单验证被绕过



我是Reactjs的新手,这是我用它创建的第一个网络应用程序,所以这可能只是一个小错误,我要请你帮我解决这个问题。基本上,我试图验证我的表单,但它不起作用。不管我是填写表格还是留空,如果我按下发送按钮,它就会被发送,完全绕过我的验证系统。这是我的表单组件,我使用emailjs来处理电子邮件发送(它非常有效(。此外,组件的状态可以毫无问题地更新,只是验证本身被绕过了。我希望你能帮助我:

class ContactForm extends React.Component {
constructor(props) {
super(props);
this.state = {
fields: { 'user_name': "", 'user_email': "" },
errors: {}
};
}
//Functions to handle form validation
handleValidation=()=> {
let fields = this.state.fields;
let errors = {};
let formIsValid = true;
//Name
if (!fields["user_name"]) {
formIsValid = false;
errors["user_name"] = "Non può essere vuoto!";
console.log("E' vuoto");
}
if (typeof fields["user_name"] !== "undefined") {
if (!fields["user_name"].match(/^[a-zA-Z]+$/)) {
formIsValid = false;
errors["user_name"] = "Inserire solo lettere";
console.log("Ci sono numeri");
}
}
//Email
if (!fields["user_email"]) {
formIsValid = false;
errors["user_email"] = "Non può essere vuoto!";
}
if (typeof fields["user_email"] !== "undefined") {
let lastAtPos = fields["user_email"].lastIndexOf('@');
let lastDotPos = fields["user_email"].lastIndexOf('.');
if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["user_email"].indexOf('@@') == -1 && lastDotPos > 2 && (fields["user_email"].length - lastDotPos) > 2)) {
formIsValid = false;
errors["user_email"] = "Email non valida";
}
}
this.setState({ errors: errors });
return formIsValid;
}
handleChange=(field, e)=> {
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({ fields });
}

sendEmail=(e)=> {
let submitSuccess = document.getElementById('success');
let submitFailed = document.getElementById('failed');
let contactNumber = document.getElementById('contact_number');
let userName = document.getElementById('user_name');
let userMail = document.getElementById('user_email');
let userMessage = document.getElementById('message');

e.preventDefault();

if (this.handleValidation) {
//Generate random 5-digit number for the contact number
contactNumber.value = Math.random() * 100000 | 0;
emailjs.sendForm(/*Parameters to send email I'm not showing here*/)
.then((result) => {
console.log(result.text);
submitSuccess.style.display = 'block';
}, (error) => {
console.log(error.text);
submitFailed.style.display = 'block';
})
} else {
alert("Ci sono errori nel form");
};

}

render() {
return (
<form className="contact-form" onSubmit={this.sendEmail}>
<input type="hidden" id="contact_number" name="contact_number" value="" />
<label style={{ fontSize: '1.3em' }}>Nome</label>
<input type="text" name="user_name" id="user_name" style={InputFormCSS} onChange={this.handleChange.bind(this, "user_name")} value={this.state.fields["user_name"]} required />
<label style={{ fontSize: '1.3em' }}>Email</label>
<input type="email" name="user_email" id="user_mail" style={InputFormCSS} onChange={this.handleChange.bind(this, "user_email")} value={this.state.fields["user_email"]} required />
<label style={{ fontSize: '1.3em' }}>Message</label>
<textarea name="message" id="message" style={TextareaFormCSS} required />
<input type="submit" value="Invia" />
<p id="success" style={{ display: 'none', backgroundColor: 'green', color: 'white', fontSize: '1.1em', borderRadius: 5, padding: 10 }}>Il messaggio è stato inviato con successo</p>
<p id="failed" style={{ display: 'none', backgroundColor: 'red', color: 'white', fontSize: '1.1em', borderRadius: 5, padding: 10 }}>Non è stato possibile inviare il messaggio</p>
</form>

);
}

}

我通过调用sendmail函数中的验证函数作为if语句的参数并使用其布尔返回值来解决这个问题,如下所示:

sendEmail=(e)=> {
let submitSuccess = document.getElementById('success');
let submitFailed = document.getElementById('failed');
let contactNumber = document.getElementById('contact_number');
let userName = document.getElementById('user_name');
let userMail = document.getElementById('user_email');
let userMessage = document.getElementById('message');

e.preventDefault();
if (this.handleValidation() == true) { ...

相关内容

  • 没有找到相关文章

最新更新