validate.js 2.36 KB
var _isInput = function(element) {
    if (!element || !element.tagName) {
      return false;
    }
    var tagName = element.tagName.toLowerCase();
    return tagName === 'input' || tagName === 'textarea';
 };

var _extend = function(out) {
	out = out || {};
	for (var i = 1; i < arguments.length; i++) {
	  var obj = arguments[i];
	  if (!obj)
	    continue;
	  for (var key in obj) {
	    if (obj.hasOwnProperty(key)) {
	      if (typeof obj[key] === 'object')
	        out[key] = _extend(out[key], obj[key]);
	      else
	        out[key] = obj[key];
	    }
	  }
	}
	return out;
};

var regExps = {
    email: /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i,
    url: /^((https?):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,
    numbers: /^\d+(\.\d{1,2})?$/,
    digits: /^[0-9]*$/,
    letters: /[a-z][A-Z]*$/
};
var Validate = function(element, options) {
    if (!_isInput(element)) {
      throw new Error('控件不存在');
    }

    if (!options.rules || Object.keys(options.rules).length === 0) {
      throw new Error('规则不存在');
    }

    var defaults = {
      regExps: regExps,
      messages: "messages"
    };
    this.options = _extend({}, defaults, options);
    this.element = element;
    this.regExps = regExps;
};
var fn = Validate.prototype;
fn.validate = function(onError) {
    var isValid = true;
    this.value = this.element.value;
    for (var rule in this.options.rules) {
      var test = this[rule];
      if (!test || typeof test !== 'function') {
        throw new Error(rule);
      }
      var param = this.options.rules[rule];

      if (!this[rule](param)) {
        isValid = false;
        this.message = "Error"//_createMessage(this.options.messages[rule], {rule: param, data: this.value});
        onError&&onError.call(null,this);
        break;
      }
    }

    if (isValid) {
      return true;
    }
};

fn.required = function() {
    return this.value.trim().length > 0;
};

fn.min = function(param) {
    return this.value.length >= param;
};

fn.max = function(param) {
    return this.value.length <= param;
};
fn.match = function(param) {
    var re = this.regExps[param];
    if (!re) {
      throw new Error(param + ':'
        + Object.keys(this.options.regExps).join(', '));
    }
    return this.regExps[param].test(this.value);
};

module.exports={
    init: Validate,
    fn: fn
};;