我正在学习简单的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
答案 0 :(得分:0)
您的问题源于在页面加载时获取输入的值,而不是在用户输入任何内容之后。尝试:
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
,但您传递的是电子邮件输入值
答案 1 :(得分:0)
代码中有很多错误。首先我在评论中说了你,你必须在document.getElementById("f_email").value;
函数内部onsubmit
。您还在内部声明变量并使用它来进行变换,例如emailVal
中声明的if
。这不起作用,你必须在if
之前声明它。用javascript控制台查看这些小错误。