【问题标题】:jQuery Validation Plugin on Django formDjango 表单上的 jQuery 验证插件
【发布时间】:2016-03-01 15:35:59
【问题描述】:

我正在尝试使用 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);

我在控制台上收到错误消息:“Uncaught ReferenceError: password1 is not defined”。
我错过了什么?

谢谢!

【问题讨论】:

  • 我相信您的模型中只有一个 password 字段。所以你不能调用fields = ("email", "first_name", "second_name", "password1", "password2"),因为它引用了Model。
  • 嗯,我不确定,因为当我删除“password2”的验证时,脚本可以工作。

标签: javascript jquery django validation django-forms


【解决方案1】:

JavaScript 中的这一行:

equalTo: password1,

...需要是一个字符串:

equalTo: 'password1',

否则 JavaScript 会认为您指的是名为 password1 的变量,而不是将元素的名称指定为字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多