利用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接收數據就好了。該插件不但在單個表單不符合驗證條件時觸發,在表單提交之前也會驗證各個表單條件,可以說是一款非常方便的表單驗證插件!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM