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

本文介绍了如何利用Parsley.js库创建一个自定义的用户名验证器,通过发送异步AJAX请求来检查用户名是否已被占用。在表单中添加特定属性,并在绑定Parsley时定义验证器函数,确保验证过程清晰且有效。同时,需要注意设置AJAX请求的异步性为false,以等待请求完成。此外,对于Parsley 2.0版本,验证器绑定方式有所改变,代码也相应进行了更新。
摘要由CSDN通过智能技术生成

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值