刚尝试使用jQuery拼凑两个函数。在表单上提交时,代码会检查是否所有字段都已填写,如果所有字段都正确,则会移动到检查电子邮件验证的另一个函数。
我认为我很接近,因为当我按下提交时,验证警报显示一毫秒然后它提交(我不想要它,因为使用的电子邮件无效)。我很确定它的代码很简单,因此我远离任何形式的验证。
以下是代码:
<script type="text/javascript">
$("#test").submit(function(){
$(".error").hide();
var isFormValid = true;
$(".required").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("highlight");
isFormValid = false;
}
else{
$(this).removeClass("highlight");
}
});
if (!isFormValid) {
document.getElementById("error").innerHTML = "You must fill in all of the fields.";
return isFormValid;
}
else {
myFunction();
}
});
function myFunction() {
var isEmailValid = true;
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if (!emailReg.test(emailaddressVal)) {
$("#email").after('<span class="error">Enter a valid email address.</span>');
isEmailValid = false;
}
else {
///ajax post function here///
}
if(!isEmailValid) {
document.getElementById("error").innerHTML = "Please enter a valid email address.";
return isEmailValid;
}
}
</script>
答案 0 :(得分:2)
试试这个:
<script type="text/javascript">
$("#test").submit(function(){
$(".error").hide();
var isFormValid = true;
$(".required").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("highlight");
isFormValid = false;
}
else{
$(this).removeClass("highlight");
}
});
if (!isFormValid) {
document.getElementById("error").innerHTML = "You must fill in all of the fields.";
return isFormValid;
}
else {
return myFunction();//should return true or false
}
});
function myFunction() {
var isEmailValid = true;
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if (!emailReg.test(emailaddressVal)) {
$("#email").after('<span class="error">Enter a valid email address.</span>');
isEmailValid = false;
}
else {
///ajax post function here///
}
if(!isEmailValid) {
document.getElementById("error").innerHTML = "Please enter a valid email address.";
return isEmailValid;
}
return isEmailValid;//should return true or false
}
</script>