dongyan6910 2016-12-31 18:03
浏览 49

PHP HTML Bootstrap - 在Bootstrap形式中使用带有PHP的验证器插件

I have a form that allows new users to be added to a database, but must this form must be 'authorised' with a valid code before being submitted. I have some PHP that works for this but the output is a crude tick or cross, indicating whether the code is valid or not. I want to instead make use of the Bootstrap Validator plugin to indicate whether the code is valid or not, however I'm not sure how to go about this. I am using the validator plugin on the form already, but it is currently only testing whether or not the field has been filled in, rather than using the PHP to test whether or not the code in the field is valid. If anyone could have a look it would be greatly appreciated.

Form.html:

<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Add New</title>
    <!-- Scripts -->
    <script src="js/jquery-3.1.1.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/validator.js"></script>
    <script src="js/validator.min.js"></script>
    <!-- CSS -->
    <link href="css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="css/bootstrap.css" rel="stylesheet">
</head>

<body>

    <div class="section text-left">
        <div class="container">
            <div class="row">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-2"></div>
                        <div class="col-md-8 col-sm-6 col-xs-12">

                            <!-- Padding -->
                            <div class="col-xs-12" style="height:30px;">
                            </div>

                            <!-- Form begins -->
                            <form action="insert_preflight.php" method="post" data-toggle="validator" data-disable="false">
                                <div class="form-group">
                                    <label class="control-label " for="first_name">First Name</label>
                                    <input class="form-control" id="first_name" maxlength="40" name="first_name" type="text" required>
                                </div>
                                <div class="form-group">
                                    <label class="control-label " for="last_name">Last Name</label>
                                    <input class="form-control" id="last_name" maxlength="40" name="last_name" type="text" required>
                                </div>
                                <div class="form-group">
                                    <label class="control-label " for="dob">Date of Birth</label>
                                    <input class="form-control" id="dob" name="dob" maxlength="10" type="date">
                                </div>
                                <div class="form-group">
                                    <label class="control-label " for="email">Email</label>
                                    <input class="form-control" type="email" id="email" name="email" type="email">
                                </div>
                                <hr>
                                <div class="form-group has-feedback" id="auth_code_form">
                                    <label for="auth_code" class="control-label ">Authorisation Code</label>
                                    <input class="form-control" id="auth_code" name="auth_code" type="password" required>
                                    <!-- <span id="auth_code_result"></span> -->
                                    <span id="auth_code_result" class="glyphicon form-control-feedback"></span>
                                </div>
                                <hr>
                                <div class="form-group">
                                    <div>
                                        <button class="btn btn-info " name="submit" type="submit">Add</button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript">
    $(document).ready(function() {
        var x_timer;
        $("#auth_code").keyup(function(e) {
            clearTimeout(x_timer);
            var auth_code = $(this).val();
            x_timer = setTimeout(function() {
                check_auth_code_ajax(auth_code);
            }, 1000);
        });

        function check_auth_code_ajax(auth_code) {
            $("#auth_code_result").html('<img src="ajax-loader.gif" />');
            $.post('check.php', {
                'auth_code': auth_code
            }, function(data) {
                $("#auth_code_result").html(data);
            });
        }
    });
    </script>

</body>
</html>

Check.php:

<?php

// Connection
include 'pdo_config.php';
try {
$conn = new PDO($dsn, $user, $pass, $opt);

$auth_code = $_POST["auth_code"];  
$stmt = $conn->prepare("SELECT * FROM tbl_instructors WHERE auth_code = :auth_code");
$stmt->bindParam(':auth_code', $auth_code);
$stmt->execute();

$exists = $stmt->fetchColumn();

if(($exists > 0)){
    die('<img src="exists.png" />');
}else{
    die('<img src="no_exists.png" />');
    }
}

catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}

$conn = null;
  • 写回答

1条回答 默认 最新

  • dongmen5867 2016-12-31 19:05
    关注

    You are using a plugin to save yourself work, but it may take way longer to figure out the plugin and how to make it work for your situation than simply rolling your own. Scary as it seems right now, writing validation code is easy.

    (The place to bring a validation plugin into the picture is if you need additional fancy validation - really precise email address validation, for example catching justme@fake.com etc).

    The first thing to determine is how to start the validation. You can validate each field as the user moves away from it (see 2nd example). You can validate on click of a button (see 1st example), or you can validate at the moment a form is submitted:

    $('myForm').submit(function(){
       //pseudo-code example
       var allOkay = true;
       for loop{
          if (field not valid) allOkay = false;
       }
       if ( !allOkay) return false; //return false: stop submit and return control to user
    });
    

    Here is an example of a roll-your-own validation:

    var chkFld, arrAll = {'One':'f1','Two':'f2','Three':'f3','Four':'f4'};
    
    $('#mybutt').click(function() {
        var errMsg='', badFlds='', firstBad='';
        for(var key in arrAll){
            chkFld = '#'+arrAll[key];
            $(chkFld).removeClass('error');
            if ($(chkFld).val() ==''){
                $(chkFld).addClass('error');
                //alert('Please complete field ' + arrAll[key] );
                errMsg += '*' + key + '
    ';
                if (firstBad=='') firstBad=chkFld;
            }
        }
        if (errMsg != '') {
            alert(errMsg);
            $(firstBad).focus();
        }
    }); //END mybutt.click
    p{width:250px;text-align:right;}
    .error{border:1px solid red;background:yellow;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <p>One: <input type="text" id="f1"></p>
    <p>Two: <input type="text" id="f2"></p>
    <p>Three: <input type="text" id="f3"></p>
    <p>Four: <input type="text" id="f4"></p>
    <br />
    <input type="button" id="mybutt" value="Go" />

    To validate from the PHP, just set one of the fields to validate using AJAX. That is, perhaps on blur() (user leaving the field) trigger an ajax lookup of the data and either do nothing (good data) or return to the field with an error condition (invalid data)

    Example:

    var chkFld, arrAll = {'One':'f1','Two':'f2','Four':'f4'};
    
    //Field 3 validation only
    $('#f3').blur(function(){
        var f3 = this.value;
       alert('You typed: ' + f3);
      $.ajax({
        type: 'post',
         url: 'ajax/my_php_validator_file.php',
        data: 'f3=' + f3,
        success: function(recd){
          if (recd!='ok'){
            $('#f3').addClass('error').focus();
          }
        }
      });
    });
    
    $('#mybutt').click(function() {
        var errMsg='', badFlds='', firstBad='';
        for(var key in arrAll){
            chkFld = '#'+arrAll[key];
            $(chkFld).removeClass('error');
            if ($(chkFld).val() ==''){
                $(chkFld).addClass('error');
                //alert('Please complete field ' + arrAll[key] );
                errMsg += '*' + key + '
    ';
                if (firstBad=='') firstBad=chkFld;
            }
        }
        if (errMsg != '') {
            alert(errMsg);
            $(firstBad).focus();
        }
        $('#myForm').submit(); //or whatever
    }); //END mybutt.click
    p{width:250px;text-align:right;}
    .error{border:1px solid red;background:yellow;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <p>One: <input type="text" id="f1"></p>
    <p>Two: <input type="text" id="f2"></p>
    <p>Three*: <input type="text" id="f3"></p>
    <p>Four: <input type="text" id="f4"></p>
    <br />
    <input type="button" id="mybutt" value="Go" />

    Here are some more simple AJAX examples to help you get the hang of it - don't just read them, reproduce them on your server and change some values. The 15 mins you spend will save you hours.

    AJAX request callback using jQuery

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格