利用BootstrapValidator插件做表单验证

BootstrapValidator插件是Github三年前的一个代码仓库了,作者现在已经不维护了,推出一个新的插件FormValidation,但是新出的这个插件是收费的,对于普通的开发人员来说,BootstrapValidator插件也够用了,这里是传送门:nghuuphuoc/bootstrapvalidator
作者提供的demo很好,涉及到不同的表单验证,自己可以修改测试不同的表单验证。我下面的代码只演示用户名和密码的验证,作为快速入门学习:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<link rel="stylesheet" href="../vendor/bootstrap/css/bootstrap.css"/>
    <link rel="stylesheet" href="../dist/css/bootstrapValidator.css"/>

    <script type="text/javascript" src="../vendor/jquery/jquery.min.js"></script>
    <script type="text/javascript" src="../vendor/bootstrap/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="../dist/js/bootstrapValidator.js"></script>
</head>
<body>
 	<form id="defaultForm" action="test.php" method="post" class="form-horizontal">	
		<div class="form-group">
            <label class="col-lg-3 control-label">Username</label>
            <div class="col-lg-5">
                <input type="text" class="form-control" name="username" />
            </div>
        </div>
		<div class="form-group">
            <label class="col-lg-3 control-label">Password</label>
            <div class="col-lg-5">
                <input type="password" class="form-control" name="password" />
            </div>
        </div>
		 <div class="form-group">
            <div class="col-lg-9 col-lg-offset-3">
                <button type="submit" class="btn btn-primary" name="signup" value="Sign up">Sign up
                </button>
            </div>
         </div>

	</form>
	<script>
		$(document).ready(function() {
			$('#defaultForm').bootstrapValidator({
				message: '填写值无效',
		        feedbackIcons: {
		            valid: 'glyphicon glyphicon-ok',
		            invalid: 'glyphicon glyphicon-remove',
		            validating: 'glyphicon glyphicon-refresh'
		        },
		        fields: {
		        	username: {
		                message: '用户名无效',
		                validators: {
		                    notEmpty: {
		                        message: '用户名不能为空'
		                    },
		                    stringLength: {
		                        min: 2,
		                        max: 6,
		                        message: '用户名的长度必须在2-6个字节'
		                    },
				        },
				    },
				    password: {
		                validators: {
		                    notEmpty: {
		                        message: '密码不能为空'
		                    },
		                   different: {
		                        field: 'username',
		                        message: '密码不能和用户名重复'
		                    }
						},
					},
				}
			});
		});
	</script>
</body>
</html>

该html页面将表单数据提交到test.php,在test.php页面中使用$_POST接收数据就好了。该插件不但在单个表单不符合验证条件时触发,在表单提交之前也会验证各个表单条件,可以说是一款非常方便的表单验证插件!

posted @ 2017-08-18 23:31  蚁象  阅读(1927)  评论(0编辑  收藏  举报