我正在尝试使用jQuery Validation Plugin处理Django表单客户端验证,并且我已经遇到了问题。
这是我的 forms.py
class CustomUserCreationForm(UserCreationForm):
"""
A form that creates a user, with no privileges, from the given email and password.
"""
email = forms.EmailField(label='', required=True, widget = forms.TextInput(
attrs = {
'placeholder': 'E-Mail',
'class': 'form-control'
}
))
first_name = forms.CharField(label='', required=True, widget = forms.TextInput(
attrs = {
'placeholder': 'First name',
'class': 'form-control'
}
))
second_name = forms.CharField(label='', required=True, widget = forms.TextInput(
attrs = {
'placeholder': 'Last name',
'class': 'form-control'
}
))
password1 = forms.CharField(label='', required=True, widget=forms.PasswordInput(attrs = {
'placeholder': 'Password',
'class': 'form-control'
}))
password2 = forms.CharField(label='', required=True, widget=forms.PasswordInput(attrs = {
'placeholder': 'Password confirmation (enter the same password as above, for verification)',
'class': 'form-control'
}))
class Meta:
model = CustomUser
fields = ("email", "first_name", "second_name", "password1", "password2")
def save(self, commit=True):
user = super(CustomUserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data['password2'])
if commit:
user.save()
return user
这是我的模板
<form id="user_form" method="post" action="/register/" enctype="multipart/form-data">
{% csrf_token %}
{{ user_form.as_p }}
<input type="submit" class="btn btn-info submit" name="submit" value="Register" />
</form>
这是验证工作的脚本
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
(function($,W,D,undefined)
{
$(D).ready(function()
{
//form validation rules
$("#user_form").validate({
rules:
{
email:
{
required: true,
email: true,
"remote":
{
url: '/check_email/',
type: "post",
data:
{
email: function()
{
return $('#register-form :input[name="email"]').val();
}
}
}
},
first_name:
{
required: true,
minlength: 3
},
second_name:
{
required: true,
minlength: 3
},
password1:
{
required: true,
minlength: 8
},
password2:
{
required: true,
equalTo: password1,
minlength: 8
}
},
messages:
{
email:
{
remote: jQuery.validator.format("{0} is already taken.")
},
},
submitHandler: function(form)
{
form.submit();
}
});
});
})(jQuery, window, document);
我在控制台上收到错误:&#34; 未捕获的ReferenceError:未定义password1 &#34;。
我错过了什么?
谢谢!
答案 0 :(得分:1)
JavaScript中的这一行:
equalTo: password1,
...需要是一个字符串:
equalTo: 'password1',
否则JavaScript认为您指的是名为password1
的变量,而不是将该元素的名称指定为字符串。