学习完一门语言时难免会有一些想法与激情来驱动我们开发,以下是本人为了学习所编写的轮子,即使别人写的再香,我也想构造一套自己的表单验证
使用
$("form.Evaluate").submit(function () {
var ModelStr = VerifiForm.GetValue({ el: ".Evaluate", VModel: VModel });
if (typeof ModelStr != "boolean") {
// console.log(ModelStr)
// ajax submit()
})
模型
- Reg: { Action: null, Notice: "" } Action 可填写正则匹配方法,不需要写括号,如您在此之前定义好了可将方法写入,例:Reg: { Action: check, Notice: "请您输入正确的数据" } *
var VModel = [
{
FieldName: "NickName",
FieldType: "input",
PseudoClass: "",
Required: true,
Reg: { Action: null, Notice: "" },
Notice: "请填入您的姓名"
},
{
FieldName: "Sex",
FieldType: "input",
PseudoClass: ":checked",
Required: true,
Reg: { Action: null, Notice: "" },
Notice: "请选择性别"
},
{
FieldName: "MsgStr",
FieldType: "textarea",
PseudoClass: "",
Required: true,
Reg: { Action: null, Notice: "" },
Notice: "请填入留言内容"
}
];
简易提交表单核心插件代码
function isEmpty(obj) {
if (typeof obj == "undefined" || obj == null || obj == "") {
return true;
} else {
return false;
}
}
function GetElemValByForm(elemtype, selector) {
var _val = "";
switch (elemtype) {
case "input":
_val = selector.val();
break;
case "textarea":
_val = selector.val();
break;
case "select":
_val = selector.val();
break;
}
return _val;
}
var VerifiForm =
{
GetValue: function (obj_new) {
var default_obj = {
el: "",
VModel: []
};
//var last_obj = Object.assign({}, default_obj, obj_new);
var last_obj = obj_new;
var _this = $(last_obj.el);
var model = {};
for (var i = 0; i < last_obj.VModel.length; i++) {
var obj = last_obj.VModel[i];
console.log(obj.FieldName);
var torclass = (obj.FieldType + "[name=" + obj.FieldName + "]" + obj.PseudoClass);
var _val = GetElemValByForm(obj.FieldType, _this.find(torclass));
if (obj.Required) {
if (!isEmpty(_val)) {
if (obj.Reg.Action != null) {
if (!obj.Reg.Action(_val)) {
//alert(obj.Reg.Notice, { icon: 5 });
alert(obj.Reg.Notice);
return false;
}
}
} else {
//alert(obj.Notice, { icon: 5 });
alert(obj.Notice);
return false;
}
}
model[obj.FieldName] = _val;
}
console.log(model);
return model;
}
};