简体   繁体   中英

Parsley remote validation is performed several times, even after successful submission

I am using Parsley in my project for form validation. One field in said form is an ID that must be unique - so I have added my own addAsyncValidator and on the backend I return 404 or 200 depending on whether an entry with the ID already exists or not.

When the form's submit button is pressed, I use

$("#frmobjectadd").submit(function(event){
    $(this).parsley().whenValidate().done(function() {
        //Ajax call to the backend to insert data here...
    }
});

to deal with the async validation issues. Validation using this method works, however, I have noticed that pretty much every time I submit the form at least three Ajax calls are made for that field alone. Furthermore, when the form is valid, the data is sent to the backend where it is successfully processed. In the XHR log, I see an AJax response that indicates that it was successful, in which case I re-direct the user to a different page. Despite that, Parsley still sends a form validation request to the remote validator which fails since it is checking whether the entry I have just inserted already exists in the DB. This leads to an error message being displayed for a short amount of time before the re-direction takes place. Is there any way to fix this?

The remote validator:

Parsley.addAsyncValidator('objectexists', function (xhr) {
     return xhr.status === 200;
}, "/backend/insert.php?formfunction=checkIfUnique&projectid=<?php echo $projectid; ?>");

The field in question

<input type="text" required
    data-parsley-remote
    data-parsley-remote-validator="objectexists"
    data-parsley-remote-message="Object name already exists."
    class="form-control" id="id" name="id" value="" placeholder="Type in object name">

Parsley initialization for the form looks like this:

    $('#frmobjectadd').parsley({
        errorClass: 'has-error',
        classHandler: function(el) {
          return el.$element.closest(".form-group");
        },
        errorsWrapper: '<span class="help-block"></span>',
        errorTemplate: "<span></span>",
        errorsContainer: function(el) {
            return el.$element.closest('.form-group');
        }
    });   

Why not let Parsley process the submit event, no need to call whenValidate either. Just listen to form:success or form:submit event instead.

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