我的问题是我想以javascript面向对象的方式验证我的表单,我无法使其工作。
<form id="contact-form" action="#" method="get">
<ul>
<li><input type="text" id='fname' name='fname' class='required' placeholder="Firstname"/></li>
<li><input type="text" id='lname' name='lname' class='required' placeholder="Lastname"/></li>
<li><input type="password" id='pwd' name='pwd' class='required' placeholder="Password"/></li>
<li><input type="password" id='confPwd' name='confPwd' class='required' placeholder="Confirm password"/></li>
<li><input type="text" id='email' name='email' class='required' placeholder="Email"/></li>
<li><input type="text" id='website' name='website' class='required' placeholder="Website"/></li>
<li>
<input type="submit" id='submit' value="Submit" />
</li>
</ul>
</form>
var formValidate = {
validate: function(elem) {
var frm = elem.attr('id');
$('.required', '#' + frm).each(function() {
if ($(this).val() === '') {
alert($(this).attr('id') + ' is a required field.'); //<---gets here
$(this).focus();
return false; // <--not returning false
}
});
}
};
$(function() {
$('form').submit(function() {
formValidate.validate($('form'));
});
});
答案 0 :(得分:3)
您需要在submit
处理程序中返回验证标志。
$(function () {
$('form').submit(function () {
return formValidate.validate($('form'));
});
});
此外,您的return语句只是中断each
函数,而不是从validate
方法返回。
validate: function (elem) {
var isValid = true;
var frm = elem.attr('id');
$('.required', '#' + frm).each(function () {
if ($(this).val() === '' && isValid) {
alert($(this).attr('id') + ' is a required field.');
$(this).focus();
isValid = false;
return false;
}
});
return isValid;
}
您可以稍微简化验证功能:
validate: function (elem) {
var isValid = true;
$('.required', elem).each(function () {
var $this = $(this);
if ($this.val() === '' && isValid) {
alert($this.attr('placeholder') + ' is a required field.');
$this.focus();
isValid = false;
return false;
}
});
return isValid;
}
答案 1 :(得分:1)
使用e.preventDefault()
$(function () {
$('form').submit(function (e) {
e.preventDefault();
formValidate.validate($('form'));
});
});
答案 2 :(得分:1)
var formValidate = {
validate: function(elem) {
var frm = elem.attr('id');
$('.required', '#' + frm).each(function() {
if ($(this).val() === '') {
alert($(this).attr('id') + ' is a required field.');
$(this).focus();
return false; // <- affects "each" scope, not function scope
}
});
}
};
将其更改为:
var formValidate = {
validate: function(elem) {
var frm = elem.attr('id');
var invalid = 0;
$('.required', '#' + frm).each(function() {
if ($(this).val() === '') {
alert($(this).attr('id') + ' is a required field.');
$(this).focus();
invalid++;
return false; // <- affects "each", therefore stopping the loop
}
});
// add these, to also return value from function
if (invalid > 0) return false;
return true;
}
};
对于你的提交处理程序:
$(function() {
$('form').submit(function() {
return formValidate.validate( $(this) ); // you must pass the returned value to your submit callback
});
});