首页 > 代码库 > vvv
vvv
//function field(options) {
// this.id = options.id; // 要验证的字段的ID
// this.vals = options.vals; // 验证器对象数组
// this.suc = options.suc; // 当验证成功的时候执行的事件
// this.err = options.err; // 当验证失败的时候执行的事件
// this.check = false; // 是否需要验证
// this.pass = true; // 是否验证通过
//}
jQuery.fn.validate = function (options) {
var opts = jQuery.extend({
containType: "input",
validatorType: "default",
fields: [],
defaultStyle: {
normalBorderColor: "#66afe9",
errBorderColor:"red",
sucCallBack: defaultSuccessCallBack,
errCallBack: defaultErrorCallBack
},
callback: function (isPass) { return; }
}, options || {});
// 容器
var jContainer = jQuery(this);
if (opts.fields.length == 0) loadData();
if (opts.fields.length == 0) return;
check();
function loadData() {
// clear
opts.fields.splice(0, opts.fields.length);
// load
jContainer.find(opts.containType).each(function () {
var $this = jQuery(this);
opts.fields.push({
id: $this.attr("id"),
check: $this.attr("check"),
suc: $this.attr("suc"),
err: $this.attr("err"),
vals: $this.attr("vals")
});
});
}
function check() {
for (var i in opts.fields) {
var field = opts.fields[i];
if (!field.check) continue;
// 过滤无效ID
var jObj = getJqObject(field.id);
if (isNullOrEmpty(jObj)) continue;
// 是否验证通过标记
var isPass = false;
// 校验
if (opts.validatorType == "default") {
isPass = defaultValidator(jObj);
} else {
isPass = customValidator(field);
}
// 校验完毕后执行
opts.callback(isPass);
}
}
function getJqObject(id) {
return $("#" + id);
}
function customValidator(field) {
var flag = true;
for (var i in field.vals) {
var validator = field.vals[i];
if (validator()) {
field.sucCallBack();
} else {
field.errCallBack();
flag = false;
}
}
return flag;
}
function defaultValidator(jObj) {
if (isNullOrEmpty(getValue(jObj))) {
return opts.defaultStyle.errCallBack(jObj);
} else {
return opts.defaultStyle.sucCallBack(jObj);
}
}
function defaultSuccessCallBack(jObj) {
jObj.css("border-color", opts.defaultStyle.normalBorderColor);
return true;
}
function defaultErrorCallBack(jObj) {
jObj.css("border-color", opts.defaultStyle.errBorderColor);
return false;
}
function getValue(jObj) {
var $valuehttp://www.mamicode.com/= "";
if (jObj.attr("type") == "radio") {
var name = jObj.attr("name");
$value = http://www.mamicode.com/$("input[name=‘" + name + "‘]:checked").val();
} else {
$value = http://www.mamicode.com/jObj.val();
}
return $value;
}
function isNullOrEmpty(object) {
return object == undefined || object == null || object == "";
}
}
function focusValidator(jObj) {
if (jObj.attr("type") == "radio") {
if (isNullOrEmpty(getValue(jObj))) {
var name = jObj.attr("name");
$("input[name=‘" + name + "‘]").get(0).focus();
return false;
}
} else {
if (isNullOrEmpty(getValue(jObj))) {
jObj.focus();
return false;
}
}
}
vvv