当前位置: 首页 > 工具软件 > Parsley.js > 使用案例 >

parsley.js ajax,validation - Parsley.js Trigger Error on AJAX - Stack Overflow

汝开畅
2023-12-01

Is there a reason why you don't want to use a custom validator?

I think it is more clear if you define a new custom validator when parsley is applied to your form.

This is how I do it:

In your input add "parsley-username":

placeholder="Username" data-required="true" parsley-username >

When you bind parsley to your form, you should define a new custom validator named "username", like this:

$( '#form' ).parsley( {

validators: {

username: function() {

return {

validate: function(val) {

var response = false;

$.ajax({

url: SITE_ROOT + "ajax/ajaxUserActions.php",

data: {'username': val, 'data': 'checkUniqueUsername'},

dataType: 'json',

type: 'get',

async: false,

success: function(data) {

if (data.total > 0)

response = false;

else

response = true;

},

error: function() {

response = false;

}

});

return response;

},

priority: 32

}

}

}

, messages: {

username: "Your username is already taken. Please insert other value"

}

} );

A few things you should be aware:

In your example, you define your URL using a PHP constant. In my code, I assume you have a javascrip variable named SITE_ROOT with the same value as the php variable. If you insert this code inside a php file, it will work with your constant (although, I do not recomend using this code inside php. It will be more clear inside a javascript file).

The ajax request must have async defined to false. This way, the rest of the code must wait for the ajax to be completed.

My code assumes that your AJAX will echo a JSON object with a property called "total". It total = 0, the username is not taken.

This code works with parsley 1.*

Update for Parsley 2.*

As of Parsley 2.0, the input will have the following attributes:

placeholder="Username" data-parsley-required data-parsley-username >

And you now must bind the validator like this:

window.ParsleyValidator

.addValidator('username', function (value, requirement) {

var response = false;

// Your code to perform the ajax, like before

return response;

}, 32)

.addMessage('en', 'username', 'Your username is already taken.');

Another possibility is to use the built in remote ajax validator (see the docs)

 类似资料: