简体   繁体   中英

Remote validation with Parsley.js

I'm trying to implement remote validation for the email field in my (Django) form, but I'm getting the error " Cannot read property 'addAsyncValidator' of undefined ".

The template (I'm using the last dist of Parsley , so the remote.parsley.js isn't needed)

<head>
<script src="{% static 'js/parsley.js' %}"></script>
</head> 

<form id="user_form" method="post" action="/register/" enctype="multipart/form-data">

    {% csrf_token %}

    <input data-parsley-remote="/check_email/"
           data-parsley-remote-message="The introduced email has already been registered!"
           data-parsley-remote-options="{ 'type': 'POST' }"
           data-parsley-remote-validator="emailAvailable"
           data-parsley-remote-reverse="false"
           data-parsley-required="true"
           data-parsley-required-message="This field is required."
           data-parsley-trigger="change"
           data-parsley-type="email"
           id="id_email"
           name="email"
           required="required"
           type="email"
           value="a@a.com"/>

    {{ user_form.as_p }}

    <input type="submit" class="btn btn-info submit" name="submit" value="Register" />
</form>

The script

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() {
            $("#user_form").parsley();
        });

        $('[name="email"]').Parsley.addAsyncValidator('emailAvailable', function (xhr) {
            var emailExists = this.$element.val().startsWith(xhr.responseJSON.email + "@");
            return !emailExists;
        }, '/check_email/');

What am I missing?

Parsley is a global variable. You need to call Parsley.addAsyncValidator(...) to setup your custom function to analyse the result of ajax calls, but not $somejQueryobject.Parsley.whatever .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM