更新jqbootstrapvalidation匹配以仅在表单提交时进行验证

时间:2013-07-14 17:23:46

标签: javascript jquery twitter-bootstrap

如何更改jqbootstrapvalidation的匹配项以仅匹配表单提交。喜欢所需的字段匹配。假设我有一个密码并重新输入密码字段。当我点击密码字段时,它在重新输入密码的错误框中说“匹配验证失败”

    <!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />

    <!--<script type="text/javascript" src="js/jquery.js"></script>-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript" src="js/test.js"></script>
    <script>
        $(function () { $("input,select,textarea").not([type=submit]").jqBootstrapValidation(); });</script><title</title></head><body>

    <form class="form-horizontal">



        <div class="control-group">
            <label class="control-label">Password</label>
            <div class="controls">
                <input type="password" name="password1" required="required" />
                <p class="help-block"></p>

            </div>

        </div>

        <div class="control-group">
            <label class="control-label">Retype Password</label>
            <div class="controls">
                <input type="password" data-validation-match-match="password1" name="password2" required="required" />
                <p class="help-block"></p>

            </div>

        </div>

        Submit:   <input type="submit" name="submitbtn" id="submitbtn" value="submit" />
    </form>

</body>

</html>

如何进行更改,以便匹配验证仅适用于表单提交。任何帮助将受到高度赞赏。

非常感谢提前。

1 个答案:

答案 0 :(得分:1)

我是通过编辑jqBootstrapvalidation.js来做到这一点的。 在validation.validationparams.submitting确定它是提交。

我需要执行带有BD访问权限的ajax。所以我创建了一个新的“验证器”(在validatorTypes: ajax_v2中),其中包含一个新属性(somenteSubmit),表示它仅用于提交。

在js的开头,包括一个新选项:

(function( $ ){

    var createdElements = [];

    var defaults = {
        options: {
            somenteSubmit:false,//indicates the validator will happen only in   submit
            prependExistingHelpBlock: false,
            sniffHtml: true, // sniff for 'required', 'maxlength', etc
            preventSubmit: true, // stop the form submit event from firing if validation fails
            submitError: false, // function called if there is an error when trying to submit
            submitSuccess: false, // function called just before a successful submit event is sent to the server
            semanticallyStrict: false, // set to true to tidy up generated HTML output
            autoAdd: {
                helpBlocks: true
            },
            filter: function () {
                // return $(this).is(":visible"); // only validate elements you can see
                return true; // validate everything
            }
        },
validation.validation中的

      // =============================================================
      //                                                    VALIDATION
      // =============================================================

      $this.bind(
        "validation.validation",
        function (event, params) {

          var value = getValue($this);
          var validar = true;


          // Get a list of the errors to apply
          var errorsFound = [];

          $.each(validators, function (validatorType, validatorTypeArray) {
            if (value || value.length || (params && params.includeEmpty) || (!!settings.validatorTypes[validatorType].blockSubmit && params && !!params.submitting)) {
              $.each(validatorTypeArray, function (i, validator) {

                  validar=true;
                  if ((!(params && params.submitting)) && (settings.validatorTypes[validatorType].somenteSubmit)) {
                      validar=false;
                  }  

                  if (validar){
                     if (settings.validatorTypes[validatorType].validate($this, value, validator)) {
                      errorsFound.push(validator.message);
                     }
                }
              });
            }
          });

          return errorsFound;
        }
      );

ValidatorTypes

  ajax_v2: {
      name: "ajax_v2",
      init: function ($this, name) {
        return {
          validatorName: name,
          url: $this.data("validation" + name + "Ajax_v2"),
          lastValue: $this.val(),
          lastValid: true,
          lastFinished: true
        };
      },
      validate: function ($this, value, validator) {

            validator.lastValue = value;
            validator.lastValid = true;
            validator.lastFinished = false;
            var resultado= $.ajax({
              url: validator.url+value,
              data: ({}),
              dataType: "html",
              async :false
            }).responseText; ;

            if (resultado=="true") {
                return true;

            }else {
                return false;

            }
      },
      blockSubmit: true,
      somenteSubmit:true //execute this new validator only in submit .
    },

JSP:

                <td>Login</td>
                <td>
                    <div class="control-group">
                        <div class="controls">
                            <input class="form-control" type="text" autofocus="" id="login" name="usuario.login" value="${usuario.login}" size="25" placeholder="Login" required=""
                            data-validation-regex-regex="^[A-Za-z\d]{8,10}$"
                            data-validation-regex-message="O Login deve conter entre oito a dez caracteres (letras ou números)."
                            data-validation-nevermatches-nevermatch="usuario.idCliente"
                            data-validation-nevermatches-message="Login não deve ser igual ao Cartão."

                            data-validation-ajax_v2-ajax_v2="${pageContext.request.contextPath}/pesquisaLogin/"
                            data-validation-ajax_v2-message="Login já existente. Favor informar outro Login." 
                            >  
                            <div class="help-block"></div>

                        </div>
                    </div>
                </td>