我有一个简单的类项目,我正在做一些表单验证。我们必须使用一些基本的正则表达式来验证输入。我在外部 js 文件中有此代码。
我有一个捕获 onsubmit 事件的函数,并返回是否继续回发的验证函数的值。
问题是当我调用 RegEx.test() 方法时,我的验证函数会停止并返回,并且回发会无意中进行。同样奇怪的是,如果我使用“new RegEx()”创建一个正则表达式对象,也会发生同样的事情。我不知道为什么。
这是我的代码:
$(document).ready(function() {
// onsubmit event
$('form').submit(
function() {
return validation();
}
);
// form validation
function validation() {
resetErrors();
//variables
var validates = true;
var errorString = "";
//var isEmail = new RegEx('^.+@.+\..+$'); // function stops here if line is uncommented and kicks off the postback?
//alert("harro new regex?"); // does not run if above line is uncommented
var isEmail = "/^.+@.+\..+$/"; // this doesn't stop the function
alert("harro isEmail direct regex string assignment"); // runs
var isZipCode = "/^(\d{5}$)|(^\d{5}-\d{4}$)/"; // this doesn't stop the function
alert("harro isZipCode direct regex string assignment"); // runs
//firstname
if (!$('#firstName').val().trim()) {
validates = false;
$('#firstName').addClass('error');
errorString += "First Name is blank. <br />";
}
//lastname
if (!$('#lastName').val().trim()) {
validates = false;
$('#lastName').addClass('error');
errorString += "Last Name is blank. <br />";
}
//email
if (!$('#email').val().trim()) {
validates = false;
errorString += "Email is blank. <br />";
$('#email').addClass('error');
}
// if this runs the test, the function stops here
else if (!isEmail.test(email.value)) {
validates = false;
errorString += "Please enter a valid email address. <br />";
$('#email').addClass('error');
}
alert("harro rest of function after email test?")// does not run if "else if" is ran
//address
if (!$('#address').val().trim()) {
validates = false;
$('#address').addClass('error');
errorString += "Address is blank. <br />";
}
//zipcode
if (!$('#zipCode').val().trim()) {
validates = false;
$('#zipCode').addClass('error');
errorString += "Zipcode is blank. <br />";
}
// if this runs the test, the function stops here
else if (!isZipCode.test(zipCode.value)) {
validates = false;
$('#zipCode').addClass('error');
errorString += "Please enter a valide zip code. <br />";
}
alert("harro rest of function after zipcide test?")// does not run if "else if" is ran
if (validates) {
return true;
}
//output error messages
$('#pageTitle').after("<p id='errorText'>" + errorString + "</p>");
return false;
}
//reset validation errors
function resetErrors() {
$('#errorText').remove();
$('#firstName').removeClass('error');
$('#lastName').removeClass('error');
$('#email').removeClass('error');
$('#address').removeClass('error');
$('#zipCode').removeClass('error');
}
});