当前位置 : 主页 > 网络编程 > JavaScript >

javascript校验类,可自己扩展正则

来源:互联网 收集:自由互联 发布时间:2021-06-30
原生js编写的validate校验插件 ;(function(window,document){var validate = function(options){if(!(this instanceof validate)){return new validate(options);}//执行初始化this.init(options);}//复制对象方法function cloneObj(oldO
原生js编写的validate校验插件
;(function(window,document){
	var validate = function(options){
		if(!(this instanceof validate)){
			return new validate(options);
		}
		//执行初始化
		this.init(options);
	}
	//复制对象方法
	function cloneObj(oldObj) {
		if (typeof(oldObj) != 'object') return oldObj;
		if (oldObj == null) return oldObj;
		var newObj = new Object();
		for (var i in oldObj)
		newObj[i] = cloneObj(oldObj[i]);
		return newObj;
	}
	//扩展对象
	function extendObj() {
	var args = arguments;
	if (args.length < 2) return;
	var temp = cloneObj(args[0]); //调用复制对象方法
	for (var n = 1; n < args.length; n++) {
		for (var i in args[n]) {
			temp[i] = args[n][i];
		}
	}
	return temp;
	}
	validate.prototype = {
		init:function(opts){
			if(!opts.hasOwnProperty("type")){
				var errmsg = "必须传入要验证的元素类型";
				console.error(errmsg);
				return {
					"status":-1,
					"msg":errmsg
				}
			}
			if(!opts.hasOwnProperty("id") && !opts.hasOwnProperty("name")){
				var errmsg = "必须传递要进行验证元素的id或name";
				console.error(errmsg);
				return {
					"status":-1,
					"msg":errmsg
				}
			}
			if(opts.hasOwnProperty("name")){
				var ele = document.getElementsByName(opts.name);
			}
			else if(opts.hasOwnProperty("id")){
				var ele = document.getElementById(opts.id);
			}
			if(ele){
				opts.ele = ele;
			}else{
				var errmsg = "页面中没有找到匹配的元素";
				console.error(errmsg);
				return {
					"status":-1,
					"msg":errmsg
				}
			}
			switch(opts.type){
				case 'email':
					return this.isEmail(opts);
					break;
				case 'chinese':
					return this.isChinese(opts);
					break;
				case 'mobile':
					return this.isMobile(opts);
					break;
				case 'password':
					this.isPwd(opts);
					break;
				case 'english':
					this.isEnglish(opts);
					break;
				case 'date':
					this.isDate(opts);
					break;
				case 'url':
					this.isUrl(opts);
					break;
				case 'cert_card':
					this.isCertCard(opts);
					break;
			}
		},
		isEmail:function(opts){
			if(opts.hasOwnProperty("expstr")){
				if(opts.hasOwnProperty("errmsg")){
					var errmsg = opts.errmsg;
				}else{
					var errmsg = "邮箱格式正确";
				}
				var expStr = opts.expstr;
			}else{
				var expStr = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
			}
			var ele = opts.ele;
			if(expStr.test(ele.value)){
				return {
					"status":0,
					"msg":errmsg
				}
			}else{
				if(opts.hasOwnProperty("errmsg")){
					var errmsg = opts.errmsg;
				}else{
					var errmsg = "您输入的邮箱格式错误,请重新输入";
				}
				return {
					"status":-1,
					"msg":errmsg
				}
			}
		}
	};
	window.validate = validate;
})(window,document);
网友评论