參考文章:https://qtdebug.com/fe-semantic-ui-validation/
實現(xiàn)注冊功能,在注冊的時候要填用戶名,為了提升用戶體驗感,要在輸入的時候就能確定這個用戶名或手機號是否能用,首先要添加自定義的驗證規(guī)則,就是利用Ajax將當前輸入框的值請求后臺,檢查用戶名或手機號是否已被注冊,
var $enrollInfo = $('.ui.form');
$.fn.form.settings.rules.checkInfo = function () {
var valid = false;
var username = {};
username.key = $(this).attr("name");
username.value = $(this).val();
syncAjaxData("POST", "/enrollCheck", JSON.stringify(username), function usernameIsExists(result) {
console.log(username.value);
valid = !result.userIsExist;
});
return valid;
};
這里Ajax是封裝了一下的,Ajax請求要是同步請求,將async設(shè)為false,async: false
,如果驗證沒通過則返回false,我這里后臺服務(wù)是如果用戶存在則返回true,所以加了個!邏輯,
完整調(diào)用代碼如下,html代碼省略,參考官方文檔就行了,
$(document).ready(function () {
var $enrollInfo = $('.ui.form');
$.fn.form.settings.rules.checkInfo = function () {
var valid = false;
var username = {};
username.key = $(this).attr("name");
username.value = $(this).val();
syncAjaxData("POST", "/enrollCheck", JSON.stringify(username), function usernameIsExists(result) {
console.log(username.value);
valid = !result.userIsExist;
});
return valid;
}
$enrollInfo.form({
inline: true,
revalidate: true,
transition: 'slide down',
on: 'blur',
fields: {
username: {
identifier: 'username',
rules: [
{
type: 'empty',
prompt: '請輸入用戶名'
},
{
type: 'checkInfo',
prompt: '此用戶名已經(jīng)被注冊了,換個名字吧!'
}
]
},
telPhone: {
identifier: 'telPhone',
rules: [
{
type: 'regExp[^[1][3,4,5,7,8][0-9]{9}$]',
prompt: '請輸入正確手機號'
},
{
type: 'different[username]',
prompt: '用戶名和手機號不能相同'
},
{
type: 'checkInfo',
prompt: '此手機號已經(jīng)注冊了,試試去登錄?'
}
]
}
}
});
});