我的代碼有問題,我真的不知道如何更正它。驗證的效果很好,但問題是,當你填寫名稱輸入字段爲例如 - 迪馬,然後你選擇手機的字段,但名稱的字段仍然沒有任何,你可以看到你填寫正確,你必須再次選擇該字段,並且只能向該字段添加一些類。我怎樣才能解決這個問題?使用javascript驗證聯繫表格
<form name="myform>
<input type="text" name="firstname" placeholder="First Name" maxlength="30">
<p id="nameError">First name is required</p>
<p id="nameErrorTwo">Enter only characters</p>
<input type="tel" name="phone" placeholder="Phone Number">
<p id="telError">Phone is required</p>
<p id="telErrorTwo">Enter a number</p>
</form>
// firstname
document.myform.firstname.onblur= function() {
var name = document.myform.firstname.value;
if (name === "") {
document.myform.firstname.removeAttribute("class", "ready");
document.myform.firstname.style.border = "1px solid #da3637";
document.getElementById("nameError").style.display = "block";
document.getElementById("nameErrorTwo").style.display = "none";
} else {
//firstname onchange
document.myform.firstname.onchange= function() {
document.myform.firstname.style.border = "1px solid #509d12";
document.getElementById("nameError").style.display = "none";
document.myform.firstname.setAttribute("class", "ready");
var pattern = new RegExp("\[a-z]+", "i");
var isValid = this.value.search(pattern) >= 0;
if (!(isValid)) {
document.myform.firstname.style.border = "1px solid #da3637";
document.getElementById("nameErrorTwo").style.display = "block";
} else {
document.getElementById("nameErrorTwo").style.display = "none";
document.myform.firstname.style.border = "1px solid #509d12";
}
};
}
};
//phone
document.myform.phone.onblur= function() {
var name = document.myform.phone.value;
if (name === "") {
document.myform.phone.removeAttribute("class", "ready");
document.myform.phone.style.border = "1px solid #da3637";
document.getElementById("telError").style.display = "block";
document.getElementById("telErrorTwo").style.display = "none";
} else {
//phone onchange
document.myform.phone.onchange= function() {
document.myform.phone.style.border = "1px solid #509d12";
document.getElementById("telError").style.display = "none";
document.myform.phone.setAttribute("class", "ready");
var pattern = new RegExp("\\d", "i");
var isValid = this.value.search(pattern) >= 0;
if (!(isValid)) {
document.myform.phone.style.border = "1px solid #da3637";
document.getElementById("telErrorTwo").style.display = "block";
} else {
document.getElementById("telErrorTwo").style.display = "none";
document.myform.phone.style.border = "1px solid #509d12";
}
};
}
};
阿爾諾非常感謝,現在它的工作原理它是如何應該做的:) –
高興它幫助。除此之外:您的原始正則表達式正在測試該名稱是否包含_至少一個字母_以及該電話是否包含_至少一個digit_。我不認爲這是預期的行爲(請參閱我編輯的解決方案)。 – Arnauld
是的,我知道我的驗證不完美,謝謝你,現在它工作得很好 –