欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jQuery轻量级表单模型验证插件

程序员文章站 2022-06-03 11:59:32
jquery插件,轻量级表单模型验证,供大家参考,具体内容如下 附上源码和demo段 var validataform = (function(model)...

jquery插件,轻量级表单模型验证,供大家参考,具体内容如下

附上源码和demo段

var validataform = (function(model) {
  model.key = "[data-required='true']";
  model.elementlist = new array();
  model.functiondictionary = new dictionary();
  model.toastrcustom = function (msg) {
    alert(msg);
  }

  model.addelement = function (name) {
    model.elementlist.push(name);
  };

  model.addfunction = function (name, func) {
    model.functiondictionary.add(name, func);
  };

  model.validata = function (formname) {
    for (var i = 0; i < model.elementlist.length; i++) {
      var thisobj = model.elementlist[i];
      var str = formname + " " + thisobj + model.key;
      var elements = $(str);

      for (var j = 0; j < elements.length; j++) {
        var element = elements.eq(j);
        var value = element.val();

        var elementtype = element.data().type;

        var func = model.functiondictionary.find(elementtype);
        if (func) {
          var result = func(value, element);

          if (result.status) {
            var errorinfo = result.message;
            model.toastrcustom(errorinfo);
            return;
          }
        }
      }
    }
  };

  model.elementlist.push("input");
  model.elementlist.push("select");
  model.functiondictionary.add("required", function (value, element) {
    var name = element.data().name;

    return {
      status: (value === ""),
      message: (value === "" && name + "不能为空")
    };
  });

  return model;
})(window.validataform || {});

调用处

<form id="validataform">
  <input data-required="true" data-name="名称" data-type="required" value="">
  <input data-required="true" data-name="昵称" data-type="hello">
  <button id="send">提交</button>
</form>
<script src="~/js/plugs/jquery-3.3.1.js"></script>
<script src="~/js/dictionary.js"></script>
<script src="~/js/validataform.js"></script>
<script type="text/javascript">
  $("#send").click(function () {
    validataform.validata("#validataform");
  });
</script>

dictionary这个对象是抄一个博主的
代码附上,内置链接

/* https://www.cnblogs.com/baiyangyuanzi/p/6689554.html */
/*字典 dictionary类*/
function dictionary() {
  this.add = add;
  this.datastore = new array();
  this.find = find;
  this.remove = remove;
  this.count = count;
  this.clear = clear;
}

function add(key, value) {
  this.datastore[key] = value;
}

function find(key) {
  return this.datastore[key];
}

function remove(key) {
  delete this.datastore[key];
}

function count() {
  /*var ss = object.keys(this.datastore).length;
  console.log("ssss  "+ss);
  return object.keys(this.datastore).length;*/
  /**/
  var n = 0;
  for (var key in object.keys(this.datastore)) {
    ++n;
  }
  return n;
}

function clear() {
  for (var key in this.datastore) {
    delete this.datastore[key];
  }
}

萌新初试前端,有写得不好的地方,望各位前辈,多多指教。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。