0

I'm trying to work on a Django form client-side validation using jQuery Validation Plugin, and I've bumbped into an issue.

This is my 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

This is my template

<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>

And this is the script to make the validation work

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);

I get an error on the console: "Uncaught ReferenceError: password1 is not defined".
What am I missing?

Thank you!

2
  • I believe that you have only one password field in your model. So you cannot call fields = ("email", "first_name", "second_name", "password1", "password2"), because it reference to Model. Commented Mar 1, 2016 at 15:56
  • Mh, I'm not sure about that, because when I remove the validation for "password2", the script works. Commented Mar 1, 2016 at 16:15

1 Answer 1

1

This line in your JavaScript:

equalTo: password1,

...needs to be a string:

equalTo: 'password1',

Otherwise JavaScript thinks you are referring to a variable named password1, instead of specifying the name of the element as string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.