var Validate = function(el, rule, msg) {
  this.el = el;
  this.rule = rule;
  this.msg = msg;
};

Validate.prototype.validate = function() {
  var el = this.el, rule = this.rule, msg = this.msg, v = el.value, pass, i = 0;
  
  while(rule.length !== i) {
    pass = rule[i](v);
    if (!pass) {
      this.failed(msg[i]);
      return this;
    }
    i++;
  }
  
  this.success();
  return this;
};

window.onload = function() {
  var u = document.getElementById('username');
  var rule = {
    notempty : function(v) {
      return v !== '';
    },
    name: function(v) {
      return /^[\w|·|。|•|.|.|(\u4e00-\u9fa5)]{2,20}$/.test(v);
    }
  };
  
  var username = new Validate(u, [rule.notempty, rule.name], ['不能为空', '请输入正确的用户名']);
  username.failed = function(msg) {
    var el = this.el,
      parent = el.parentNode,
      require = parent.querySelector('.require'),
      errtip = parent.querySelector('.errtip'),
      textnode = document.createTextNode(msg),
      span = document.createElement('span');
    
    if (errtip) {
      errtip.style.display= 'inline';
      errtip.innerHTML = msg;
      return this;
    } 
    
    span.appendChild(textnode);
    span.classList.add('errtip'); span.style.color = 'red';
    parent.insertBefore(span, require.nextElementSibling);
    return this;
  };
  
  username.success = function() {
    var el = this.el;
    var errtip = el.parentNode.querySelector('.errtip');
    if (errtip) {
      errtip.innerHTML = '';
      errtip.style.display = 'none';
    }
    return this;
  }
  username.validate();
  window.username = username;
};

erichooooow
229 声望5 粉丝

simple is not easy