在大部分网站里,用户名都是唯一的,即当用户注册时,如果用户输入的名字不合法,我们需要提示用户,让用户再起个新名字,而这种复杂的验证一般是通过JS来实现的,如果把它集成到ko里,那就完美了.有了这个想法,我开始尝试它,相信一定可以成功的!
起初在设计时出现了很多问题,如ajax异步问题,延时处理问题,ajax返回值问题等等,经过几次失败后,在总结了相关知识后,终于设计出来了一个不错的扩展,即 ajaxData验证方式.
扩展ko.validation.js代码
kv.rules['ajaxData'] = {
validator: function (val, ajaxMethod) {
var result = true;
$.when(ajaxMethod(val)).then(function (data) {
result = kv.utils.isEmptyVal(val) || data; //val为空走reqired逻辑,不为空再走ajax逻辑
});
return result;
},
message: 'Please enter info is no corrent.'
};
HTML代码
function existUser(name) {
return $.ajax({ //必须加return才可以将它返回
url: "/ef/IsNotExist?name=" + name,
type: "get",
dataType: "json",
async: false,
success: function (data) {
return data;
}
});
}
调用方式
self.UserName = ko.observable().extend({
minLength: ,
maxLength: { params: , message: "名称最大长度为30个字符" },
required: {
params: true,
message: "请输入名称"
},
ajaxData: {
params: existUser,
message: "用户已经存在"
}
});
运行后的效果如图
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAX4AAACtCAIAAAA4ZYOeAAAUd0lEQVR4nO2df2wTZ5rHH8lCUWpULtyFjZSWcoWWXRAYkogNlKpNt3B715Zuhe7QtbXolspR766RN3T3bi1X6e3CqYa6jgXVoqxAldw17JL20oVoQ33bbVFDV2UpyzrUTUs3KY29ARRCNxFtgul7f7ye8cx4xp44E+aN/f2IP2D8zg/nefzheZ93nCEGAAA3HLL7AgAA5QjUAwCwAagHAGADUA8AwAagHgCADUA9AAAbgHoAADYA9QAAbADqAQDYANQDALABqAcAYANQDwDABqAeAIANTE09/V1BIiKq6e4bzj8yPTn6mwO7Vv39yiNnksrtpzp3L1m6ZteBo8nL4yZPOnSycz4REf3w572al5IfHn+4bq3mFCZ585UXvtO4bFmTd0R12YlG58233nbHq+8MFnFMAIBJZko9V0fi91Y7iWj+4s2Dk2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DjBQGBEBmox3qsf5AdKBa7cwEY8v/ksN7byiYiXgAAAABJRU5ErkJggg==" alt="" />
最后要说明的一点是,目前ajax只能使用同步方式,因为在ko.validation内部有一个机制,如果程序没有返回,那么验证会返回false,即验证失败,如对于异步请求来说,它不会阻塞当前线程的执行,所以,它会直接输出false,而不走我们的验证程序.