bootstrap实现表单验证(正则表达式)

1.源码下载

2.HTML




    
    
    
    bootstrap
        


	

2.js

js有详细注释

$(function(){

	var userReg = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/;

	var pwdReg = /^[a-zA-Z]\w{5,17}$/;
	//匹配正则表达式
	validateForm($('#text'),userReg,$('#div1'));

	validateForm($('#pwd'),pwdReg,$('#div2'));

	function validateForm($obj,reg,$div){

		$obj.on({
		//失去焦点是
		blur:function(){
			//得到表单内的值
			var val = $(this).val();
			//正则表达式匹配
			if(reg.test(val)){
				//符合正则规则
				$(this).attr('index','1');
				$div.addClass(" has-success");
				$div.removeClass(" has-error");
				$div.find($obj.next()[0]).removeClass('glyphicon-remove');
			}else{
				//不符合正则
				$(this).attr('index','0');
				$div.removeClass(" has-success");
				$div.addClass(" has-error");
				$div.find($obj.next()[0]).removeClass('hidden');
				$div.find($obj.next()[0]).addClass('glyphicon-remove');
			}

		},

		focus:function(){

			$(this).val("");

		}

	})

	}

	$('button').click(function(){

		var att1 =parseInt($('#text').attr('index'));
		var att2 =parseInt($('#pwd').attr('index'));

		if(att1&&att2){

			$('form').submit();

		}

		return false;

	})

})	

 

 

你可能感兴趣的:(js)