帝国模板之家为广大用户提供专业、一站式建站服务。

网页特效

网页特效栏目收集了最全最新的前端网页插件,包括最流行的jQuery,Bootstrap,Js,Css,Vue等主流特效插件。

当前位置:首页 > 资源 > 网页特效 > 正文

js简易快速表单验证插件(Wellidate)

帝国模板之家 2020-11-18 网页特效 评论

Wellidate是一个快速、易于使用的JavaScript表单验证插件,它支持本地HTML5验证属性和HTML数据属性。

功能:

  • 自动将焦点移到无效的表单域。

  • 自定义错误消息和样式。

  • 20个内置验证规则。

  • 允许包含/排除表单字段。

  • 允许在摘要容器中显示结果。

验证规则包括:

  1. accept

  2. date

  3. digits

  4. email

  5. equalto

  6. filesize

  7. greater

  8. integer

  9. length

  10. lower

  11. max

  12. maxlength

  13. min

  14. minlength

  15. number

  16. range

  17. regex

  18. remote

  19. required

  20. step

使用方法:

1.在页面中加载wellidate.js

<script src="src/wellidate.js"></script>

2.创建表单验证规则

<form>  
<label for="data-name">Name</label>  
<input name="data-name" data-val-required="" data-val-length="" data-val-length-max="10">  
<span data-valmsg-for="data-name"></span>  
<button>Submit</button></form>
<!-- OR -->
<form>
  <label for="data-name">Name</label>
  <input name="data-name" required minlength="2" maxlength="10">
  <span data-valmsg-for="data-name"></span>
  <button>Submit</button>
</form>

3.初始化插件

new Wellidate(document.querySelector('form'));

4.自定义表单验证的所有可能选项。可以将以下选项作为对象传递给Wellidate方法。

new Wellidate(document.querySelector('form'),{
 
    // moves the focus to the invaild field
    focusInvalid: true,

    // configurable submit handler
    submitHandler: null,

    // moves the focus to the field after clean up
    focusCleanup: false,

    // includes the following form fields
    include: 'input,textarea,select',

    // for displaying results
    summary: {
      container: '[data-valmsg-summary=true]',
      show: function (result) {
        if (this.container) {
          var summary = document.querySelector(this.container);

          if (summary) {
            summary.innerHTML = '';

            if (result.isValid) {
              summary.classList.add('validation-summary-valid');
              summary.classList.remove('validation-summary-errors');
            } else {
              summary.classList.add('validation-summary-errors');
              summary.classList.remove('validation-summary-valid');

              var list = document.createElement('ul');

              result.invalid.forEach(function (invalid) {
                var item = document.createElement('li');

                item.innerHTML = invalid.message;

                list.appendChild(item);
              });

              summary.appendChild(list);
            }
          }
        }
      },
      reset: function () {
        this.show({
          isValid: true,
          invalid: []
        });
      }
    },

    // default classes
    classes: {
      inputPending: 'input-validation-pending',
      inputError: 'input-validation-error',
      inputValid: 'input-validation-valid',
      fieldPending: 'input-validation-pending',
      fieldError: 'field-validation-error',
      fieldValid: 'field-validation-valid',
      wasValidated: 'was-validated'
    },

    // excludes following form fields
    excludes: [
      'input[type=button]',
      'input[type=submit]',
      'input[type=image]',
      'input[type=reset]',
      ':disabled'
    ],

    // basic rules
    rule: {
      trim: true,
      message: 'This field is not valid.',
      isValid: function () {
          return false;
      },
      isEnabled: function () {
          return true;
      },
      formatMessage: function () {
        return this.message;
      },
      normalizeValue: function (element) {
        element = element || this.element;
        var value = element.value;

        if (element.tagName == 'SELECT' && element.multiple) {
          return [].filter.call(element.options, function (option) {
            return option.selected;
          }).length;
        } else if (element.type == 'radio') {
          if (element.name) {
            var name = this.wellidate.escapeAttribute(element.name);
            var checked = document.querySelector('input[name="' + name + '"]:checked');

            value = checked ? checked.value : '';
          } else {
            value = element.checked ? value : '';
          }
        } else if (element.type == 'file') {
          if (value.lastIndexOf('\\') >= 0) {
            value = value.substring(value.lastIndexOf('\\') + 1);
          } else if (value.lastIndexOf('/') >= 0) {
            value = value.substring(value.lastIndexOf('/') + 1);
          }
        }

        return this.trim ? value.trim() : value;
      }
    }
  
});

5.默认验证规则。根据需要重写以下验证规则。

new Wellidate(document.querySelector('form'),{
    rules: {
      required: {
          message: 'This field is required.',
          isValid: function () {
              return Boolean(this.normalizeValue());
          }
      },
      equalto: {
          message: 'Please enter the same value again.',
          isValid: function () {
              var other = document.getElementById(this.other);

              return other && this.normalizeValue() == this.normalizeValue(other);
          }
      },
      length: {
          message: 'Please enter a value between {0} and {1} characters long.',
          isValid: function () {
              var length = this;
              var value = length.normalizeValue();

              return (length.min == null || length.min <= value.length) && (value.length <= length.max || length.max == null);
          },
          formatMessage: function () {
              var length = this;

              if (length.min != null && length.max == null && !length.isDataMessage) {
                  return Wellidate.prototype.rules.minlength.message.replace('{0}', length.min);
              } else if (length.min == null && length.max != null && !length.isDataMessage) {
                  return Wellidate.prototype.rules.maxlength.message.replace('{0}', length.max);
              }

              return length.message.replace('{0}', length.min).replace('{1}', length.max);
          }
      },
      minlength: {
          message: 'Please enter at least {0} characters.',
          isValid: function () {
              return this.min == null || !parseFloat(this.min) <= this.normalizeValue().length;
          },
          formatMessage: function () {
              return this.message.replace('{0}', this.min);
          }
      },
      maxlength: {
          message: 'Please enter no more than {0} characters.',
          isValid: function () {
              return this.normalizeValue().length <= this.max || !parseFloat(this.max);
          },
          formatMessage: function () {
              return this.message.replace('{0}', this.max);
          }
      },
      email: {
          message: 'Please enter a valid email address.',
          isValid: function () {
              return /^$|^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(this.normalizeValue());
          }
      },
      integer: {
          message: 'Please enter a valid integer value.',
          isValid: function () {
              return /^$|^[+-]?\d+$/.test(this.normalizeValue());
          }
      },
      number: {
          message: 'Please enter a valid number.',
          scaleMessage: 'Please enter a value with no more than {0} fractional digits',
          precisionMessage: 'Please enter a value using no more than {0} significant digits',
          isValid: function () {
              return /^$|^[+-]?(\d+|\d{1,3}(,\d{3})+)?(\.\d+)?$/.test(this.normalizeValue());
          }
      },
      digits: {
          message: 'Please enter only digits.',
          isValid: function () {
              return /^\d*$/.test(this.normalizeValue());
          }
      },
      date: {
          message: 'Please enter a valid date.',
          isValid: function () {
              return /^$|^\d{4}-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$/.test(this.normalizeValue());
          }
      },
      range: {
          message: 'Please enter a value between {0} and {1}.',
          isValid: function () {
              var range = this;
              var value = range.normalizeValue2();

              return !value || (range.min == null || range.min <= parseFloat(value)) && (parseFloat(value) <= range.max || range.max == null);
          },
          formatMessage: function () {
              var range = this;

              if (range.min != null && range.max == null && !range.isDataMessage) {
                  return Wellidate.prototype.rules.min.message.replace('{0}', range.min);
              } else if (range.min == null && range.max != null && !range.isDataMessage) {
                  return Wellidate.prototype.rules.max.message.replace('{0}', range.max);
              }

              return range.message.replace('{0}', range.min).replace('{1}', range.max);
          }
      },
      min: {
          message: 'Please enter a value greater than or equal to {0}.',
          isValid: function () {
              var value = this.normalizeValue();

              return !value || !parseFloat(this.value) || this.value <= parseFloat(value);
          },
          formatMessage: function () {
              return this.message.replace('{0}', this.value);
          }
      },
      max: {
          message: 'Please enter a value less than or equal to {0}.',
          isValid: function () {
              var value = this.normalizeValue();

              return !value || !parseFloat(this.value) || parseFloat(value) <= this.value;
          },
          formatMessage: function () {
              return this.message.replace('{0}', this.value);
          }
      },
      greater: {
          message: 'Please enter a value greater than {0}.',
          isValid: function () {
              var value = this.normalizeValue();

              return !value || !parseFloat(this.than) || this.than < parseFloat(value);
          },
          formatMessage: function () {
              return this.message.replace('{0}', this.than);
          }
      },
      lower: {
          message: 'Please enter a value lower than {0}.',
          isValid: function () {
              var value = this.normalizeValue();

              return !value || !parseFloat(this.than) || parseFloat(value) < this.than;
          },
          formatMessage: function () {
              return this.message.replace('{0}', this.than);
          }
      },
      step: {
          message: 'Please enter a multiple of {0}.',
          isValid: function () {
              var value = this.normalizeValue();

              return !value || !parseFloat(this.value) || parseFloat(value) % this.value == 0;
          },
          formatMessage: function () {
              return this.message.replace('{0}', this.value);
          }
      },
      filesize: {
          page: 1024,
          message: 'File size should not exceed {0} MB.',
          isValid: function () {
              var size = [].reduce.call(this.element.files, function (total, file) {
                  return total + file.size;
              }, 0);

              return size <= this.max || this.max == null;
          },
          formatMessage: function () {
              var filesize = this;
              var mb = (filesize.max / filesize.page / filesize.page).toFixed(2);

              return filesize.message.replace('{0}', mb.replace(/[.|0]*$/, ''));
          }
      },
      accept: {
          message: 'Please select files in correct format.',
          isValid: function () {
              var filter = this.types.split(',').map(function (type) {
                  return type.trim();
              });

              var correct = [].filter.call(this.element.files, function (file) {
                  var extension = file.name.split('.').pop();

                  for (var i = 0; i < filter.length; i++) {
                      if (filter[i].indexOf('.') == 0) {
                          if (file.name != extension && '.' + extension == filter[i]) {
                              return true;
                          }
                      } else if (/\/\*$/.test(filter[i])) {
                          if (file.type.indexOf(filter[i].replace(/\*$/, '')) == 0) {
                              return true;
                          }
                      } else if (file.type == filter[i]) {
                          return true;
                      }
                  }

                  return !filter.length;
              });

              return this.element.files.length == correct.length;
          }
      },
      regex: {
          message: 'Please enter value in a valid format. {0}',
          isValid: function () {
              var value = this.normalizeValue();

              return !value || !this.pattern || new RegExp(this.pattern).test(value);
          },
          formatMessage: function () {
              return this.message.replace('{0}', this.title || '');
          }
      },
      remote: {
          type: 'get',
          message: 'Please fix this field.',
          isValid: function (validatable) {
              var remote = this;

              if (remote.request && remote.request.readyState != 4) {
                  remote.request.abort();
              }

              clearTimeout(remote.start);
              remote.start = setTimeout(function () {
                  if (validatable.isValid) {
                      remote.request = new XMLHttpRequest();
                      remote.request.open(remote.type, remote.buildUrl(), true);
                      remote.request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

                      remote.request.onload = function () {
                          if (validatable.isValid && 200 <= this.status && this.status < 400) {
                              remote.apply(validatable, this.responseText);
                          }
                      };

                      remote.prepare(validatable);

                      remote.request.send();

                      validatable.pending();
                  }
              }, 1);

              return true;
          },
          buildUrl: function () {
              var remote = this;
              var url = remote.url.split('?', 2)[0];
              var fields = (remote.additionalFields || '').split(',').filter(Boolean);
              var query = (remote.url.split('?', 2)[1] || '').split('&').filter(Boolean);

              for (var i = 0; i < fields.length; i++) {
                  var element = document.querySelector(fields[i]);
                  var value = remote.normalizeValue(element) || '';

                  query.push(encodeURIComponent(element.name) + "=" + encodeURIComponent(value));
              }

              query.push(encodeURIComponent(remote.element.name) + "=" + encodeURIComponent(remote.normalizeValue() || ''));

              return url + '?' + query.join('&');
          },
          prepare: function () {
          },
          apply: function (validatable, response) {
              var result = JSON.parse(response);

              if (result.isValid === false) {
                  validatable.error('remote', result.message);
              } else {
                  validatable.success(result.message);
              }
          }
      }
    }
});

6.API方法

var instance = new Wellidate(document.querySelector('form'));

// checks if is valid
instance.isValid(fieldName);

// Validates all or selected fields
instance.form();

// Validates the form and returns the validation results for each field
instance.validate();

// rebuilds the instnace
instance.rebuild();

// applies rules to fields
instance.apply({
  '#name': {
    error: 'Enter a unique name'
  },
  // ...
});

// resets the form
instance.reset();

会员登陆后即可下载资源文件。更多好用网站特效插件,请关注帝国模板之家

认为总有一天可以做成的事,不如从现在开始就着手,因为只要有开始,相信成功才会近一步。

已有 位小伙伴发表了看法

欢迎 发表评论

  • 匿名发表

关于

帝国cms模板

网页插件

帝国模板之家 | www.moyouyouw.cn

本站所有模板/文章除标明原创外,均来自网络转载,版权归原作者所有,如果有侵犯到您的权益,请联系站长删除,谢谢! 寻找帝国cms模板首选帝国模板之家,用心做站,上线至今广受好评,值得信赖!

  • 交流群1:帝国cms交流群1
  • 交流群2:帝国cms交流群2
在线QQ 给我留言