验证输入min-max字

时间:2016-12-23 21:08:58

标签: javascript html css

var validateForm = (function() {
  var options = {};
  var classError = 'error';

  var showFieldValidation = function(input, inputIsValid) {
    if (!inputIsValid) {
      if (!input.parentNode.className || input.parentNode.className.indexOf(options.classError) == -1) {
        input.parentNode.className += ' ' + options.classError

      }
    } else {
      var regError = new RegExp('(\\s|^)' + options.classError + '(\\s|$)');
      input.parentNode.className = input.parentNode.className.replace(regError, '');

    }
  };

  var testInputText = function(input) {
    var fieldHasError = false;
    var mailReg = new RegExp('^[0-9a-zA-Z_.-]', 'gi');

    if (!mailReg.test(input.value)) {
      showFieldValidation(input, false);
      return false;
    } else {
      showFieldValidation(input, true);
      return true;
    }
  };;

  var prepareElements = function() {
    var elements = options.form.querySelectorAll('input[required]');

    [].forEach.call(elements, function(element) {
      element.removeAttribute('required');
      element.className += ' required';

      if (element.nodeName.toUpperCase() == 'INPUT') {
        var type = element.type.toUpperCase();

        if (type == 'TEXT') {
          element.addEventListener('keyup', function() {
            testInputText(element)
          });
          element.addEventListener('blur', function() {
            testInputText(element)
          });
        }

      }

    });
  };
  var formSubmit = function() {
    options.form.addEventListener('submit', function(e) {
      e.preventDefault();

      var validated = true;

      //pobieramy wszystkie pola, którym wcześniej ustawiliśmy klasę .required
      var elements = options.form.querySelectorAll('.required');

      //podobne działanie już robiliśmy przy przygotowywaniu pól
      [].forEach.call(elements, function(element) {
        if (element.nodeName.toUpperCase() == 'INPUT') {
          var type = element.type.toUpperCase();

          if (type == 'TEXT') {
            if (!testInputText(element)) validated = false;
          }

        }
      });

      if (validated) {
        this.submit();
      } else {
        return false;
      }
    });
  };

  var init = function(_options) {
    //do naszego modulu bedziemy przekazywac opcje
    options = {
      form: _options.form || null,
      classError: _options.classError || 'error'

    }
    if (options.form == null || options.form == undefined || options.form.length == 0) {
      console.warn('validateForm: bad form');
      return false;
    }
    prepareElements();
    formSubmit();
  };

  return {
    init: init
  }
})();

document.addEventListener("DOMContentLoaded", function() {
  var form = document.querySelector('.form');
  validateForm.init({
    form: form
  })
});
input[type=text].as_tags_in_l67:focus {
  outline-style: none;
}
.form .error input[type=text] {
  color: #DB083E;
  border-color: #DB083E;
  box-shadow: 0 0 2px 2px red;
}
<form class="form">
  <div class="ask_con_area67">

    <div id="til_bo_x43">
      <label class="til_l67">Title</label>
      <input class="til_l67_text" type="text" autocomplete="off" required/>
    </div>

  </div>
</form>

您好, 我有一个问题,我如何更改我的代码以显示输入一些文本,例如'应该添加最少5个字符'?以及如何在验证中将min-length添加为5个字符,将max-length添加为100个字符?

1 个答案:

答案 0 :(得分:1)

注意,css处的属性选择器的值需要在引号内封闭。

input[type=text]

不是css的有效属性选择器。替换为

input[type="text"]

您可以将html5 pattern属性与RegExp ^[0-9a-zA-Z_.-]{5,100} <input type="text">元素,<label>元素for属性值一起使用设置为id元素的<input>以显示

  

&#39;应该添加最少5个字符&#39;

css :after伪元素content使用:invalid:valid伪类。

替换重复minlength maxlength属性的data-min-lengthdata-*属性

&#13;
&#13;
input[type="text"].til_l67_text:invalid + [for="til_167"] {
  color: red;
}
input[type="text"].til_l67_text:valid + [for="til_167"] {
  display: none;
}
label[for="til_167"]:after {
  content: "'should add min 5 characters'";
}
&#13;
<form class="form">
  <div class="ask_con_area67">

    <div id="til_bo_x43">
      <label class="til_l67">Title</label>
      <input class="til_l67_text" 
             id="til_167" 
             type="text" 
             minlength="5" 
             maxlength="100" 
             autocomplete="off" 
             pattern="^[0-9a-zA-Z_.-]{5,100}" 
             required/>
      <label for="til_167"></label>
    </div>

  </div>
</form>
&#13;
&#13;
&#13;