[英]validating an email with javascript
我正在學習簡單的javascript表單驗證,我很好奇為什么我的電子郵件驗證無法正常工作。 我試圖從電子郵件輸入字段中獲取信息,並使用RegEx運行我的功能。 任何幫助,將不勝感激。
小提琴演示: http : //jsfiddle.net/6SWj4/
(function(){
var emailAddr = document.getElementById("f_email").value;
console.log(emailAddr);
// console.log(email.test(str));
//
// if(email.test(str) == true){
// console.log("true");
// }else{
// console.log("false");
// }
myform.onsubmit = function(e){
//Below is one example of the validateField call with an argument.
//You must dynamically retrieve the ID name from the DOM/HTML.
validateField(emailAddr); //id = is the form input field ID
e.preventDefault();
return false;
};
var validateField = function(inputName){
if (inputName.name === 'f_email'){
var pattern = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
var emailVal = new RegExp(pattern);
//You will need to create an else-if statement for each input field id. The
// format will be similar to the above IF statement.
}else{
console.log("not valide");
}
var pass = emailVal.test(inputName);
console.log(pass);
var errorMsg = inputName.nextSibling.nextSibling.nextSibling.nextSibling;
if (!pass || inputName.value.length < 2){
errorMsg.style.display='block';
inputName.style.backgroundColor = 'red';
} else if (pass && inputName.value.length > 5){
errorMsg.style.display='none';
inputName.style.backgroundColor = 'green';
} else {
errorMsg.style.display='none';
inputName.style.backgroundColor = 'white';
};
};
})(); // end wrapper
您的問題源於在頁面加載時獲取輸入值,而不是在用戶輸入任何內容之后。 嘗試:
myform.onsubmit = function(e){
/* get value withing submit handler*/
var emailAddr = document.getElementById("f_email").value;
console.log(emailAddr);
//Below is one example of the validateField call with an argument.
//You must dynamically retrieve the ID name from the DOM/HTML.
validateField(emailAddr); //id = is the form input field ID
e.preventDefault();
return false;
};
validateField()
缺陷。 預期參數為inpuname
但您正在傳遞電子郵件輸入值
您在代碼中有很多錯誤。 首先,我在評論中document.getElementById("f_email").value;
,您必須執行document.getElementById("f_email").value;
在onsubmit
函數內部。 您還需要在某些內容中聲明變量並在其中使用變量,例如,您在if
聲明的emailVal
。 那行不通,您必須在if
之前聲明它。 使用JavaScript控制台檢查這些小錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.