问题
I have a registration form split into blocks that was working perfectly using this code based on one of the examples from the website:
$('.register-next').on('click', function () {
var current = $(this).data('currentBlock'),
next = $(this).data('nextBlock');
console.log('current block = ' + current);
console.log('next block = ' + next);
// only validate going forward. If current group is invalid, do not go further
// .parsley().validate() returns validation result AND show errors
if (next > current)
if (false === $('#form-register').parsley().validate('block' + current))
return;
// validation was ok. We can go on next step.
$('.block' + current)
.removeClass('show')
.addClass('hidden');
$('.block' + next)
.removeClass('hidden')
.addClass('show');
});
I then wanted to add an additional ajax validation to the last block of the code to make sure that the username was not already taken. I have the check working but the problems is that the form will now not submit when the validation checks are passed. Clicking on the submit button just calls the remote function again.
I am assuming that I have to reassign the function of the submit button once all validation checks have been made?
The ID username relates to the input field in the last block of my form.
Thanks
$('#username').parsley().addAsyncValidator(
'validateUsername', function (xhr) {
var UserLogin = $('#username').parsley();
window.ParsleyUI.removeError(UserLogin,'errorUsername');
if(xhr.status == '200'){
console.log("in 200");
return;
}
if(xhr.status == '404'){
response = $.parseJSON(xhr.responseText);
console.log("username exists");
window.ParsleyUI.addError(UserLogin,'errorUsername',response.error);
}
}, 'inc/check_username.php'
);
回答1:
I finally got this working. There is probably a far easier way to do it but this works.
firstly, I made one mistake with my code, I needed to return true if the status was 200
$('#username').parsley().addAsyncValidator(
'validateUsername', function (xhr) {
var UserLogin = $('#username').parsley();
window.ParsleyUI.removeError(UserLogin,'errorUsername');
if(xhr.status == '200'){
return true;
}
if(xhr.status == '404'){
response = $.parseJSON(xhr.responseText);
console.log("username exists");
window.ParsleyUI.addError(UserLogin,'errorUsername',response.error);
}
}, 'inc/check_username.php'
);
I then added an additional piece of code to listen for the submit button to be clicked and remove parsley validation from the form before using javascript to submit
$('#new-user-submit').click(function(){
$('#form-register').parsley().asyncValidate()
.done(function(){
$('#form-register').parsley().destroy();
$('#form-register').submit(); });
});
I'm not a big user of javascript so it normally takes me a while to work my way through these things but I thought with parsley being so popular there would be far better support and documentation for it.
来源:https://stackoverflow.com/questions/25763943/parsley-js-submit-form-not-working-when-using-addasyncvalidator-and-remote