我正在尝试使用jquery validate和ajax提交表单。但是它不起作用。它都会抛出任何错误。
这是html
{% if form %}
<form method="POST" action="." id="change_password_form">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="action" value="{% trans 'change password' %}"/>
</form>
{% else %}
<p>{% trans 'Your password is now changed.' %}</p>
{% endif %}
这是脚本
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>
<script type="text/javascript">
$(function() {
$("#change_password_form").validate({
rules: {
password1: {
required: true,
maxlength:10
},
password2: {
required: true,
maxlength:10
},
},
messages: {
password1: {
required: "Please provide a password",
},
password2: {
required: "Please Confirm your password",
},
},
submitHandler: function(form) {
var pass = $('input[name=password1]').val();
var repass = $('input[name=password2]').val();
if (pass != repass) {
console.log("error")
}
else {
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
})
.done(function (response) {
$('#loading-image').hide();
if (response.location == 'accounts/password/reset/key/done/'){
window.location = "{% url 'home' %}"
}
}).error(function(response){
console.log(response)
});
return false;
}
});
});
</script>
某种程度上提交事件没有发生?我该怎么做才能使用ajax和jquery验证提交表单
答案 0 :(得分:0)
我在你的代码中做了一些小改动,我认为你有一个错字。
问题是你使用的规则没有&#34;&#34;和jquery.validate无法识别。
我还添加了一个自定义验证来控制密码是否相同,所有验证都应该使用标准规则或习惯,但是您不应该在submitHandler方法中添加验证。
$("#change_password_form").validate({
rules: {
"password1": {
required: true,
maxlength:10,
"isSamePassword": true
},
"password2": {
required: true,
maxlength:10,
"isSamePassword": true
}
},
messages: {
"password1": {
required: "Please provide a password",
maxlength:"Max 10",
isSamePassword: "Pwd no son iguales"
},
"password2": {
required: "Please provide a password",
maxlength:"Max 10",
isSamePassword: "Pwd no son iguales"
}
},
submitHandler: function(form) {
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
})
.done(function (response) {
$('#loading-image').hide();
if (response.location == 'accounts/password/reset/key/done/'){
window.location = "{% url 'home' %}"
}
}).error(function(response){
console.log(response)
});
}
});
$.validator.addMethod("isSamePassword", function(value) {
var pass = $('input[name=password1]').val();
var repass = $('input[name=password2]').val();
return pass === repass;
}, 'Pwd no son iguales');