jQuery 如何在 Bootstrap Validation 中创建自定义验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26880613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:19:01  来源:igfitidea点击:

How to create a custom validation in Bootstrap Validation

jqueryhtmlspringjqbootstrapvalidation

提问by Andrew

My Goal is to validate a specific text field where this field is dependent to the value of the other element.

我的目标是验证一个特定的文本字段,其中该字段依赖于其他元素的值。

For example i have select tag and input text tag,

例如我有选择标签和输入文本标签,

input text is required when select tag has a selected value.

选择标记具有选定值时需要输入文本。

hope someone could help.

希望有人能帮忙。

回答by mavarazy

Take a look at

看一眼

http://bootstrapvalidator.com/

http://bootstrapvalidator.com/

In our project we are using, Backbone validator, integrated with Bootstrap

在我们的项目中,我们使用的是与 Bootstrap 集成的 Backbone 验证器

https://github.com/thedersen/backbone.validation

https://github.com/thedersen/backbone.validation

Sample of integration Backbone.validation & Bootstrap

集成 Backbone.validation 和 Bootstrap 的示例

[jsfiddle.net/thedersen/c3kK2/][1]

That is if you are using Backbone :)

也就是说,如果您使用的是 Backbone :)

For bootstrapvalidatorthere is a callbackmethod for validation

对于bootstrapvalidator,有一个用于验证的回调方法

http://bootstrapvalidator.com/validators/callback/

http://bootstrapvalidator.com/validators/callback/

From example:

从示例:

  <input type="text" class="form-control" name="captcha"
                data-bv-callback="true"
                data-bv-callback-message="Wrong answer"
                data-bv-callback-callback="checkCaptcha" />

And JS

和JS

function checkCaptcha(value, validator) {
    // Determine the numbers which are generated in captchaOperation
    var items = $('#captchaOperation').html().split(' '),
        sum   = parseInt(items[0]) + parseInt(items[2]);
   return value == sum;
};

$(document).ready(function() {
    // Return a random number between min and max
    function randomNumber(min, max) {
       return Math.floor(Math.random() * (max - min + 1) + min);
    };

    // Generate a sum of two random numbers
    function generateCaptcha() {
        $('#captchaOperation').html([randomNumber(1, 100), '+', randomNumber(1, 200), '='].join(' '));
    };

    generateCaptcha();

    $('#callbackForm').bootstrapValidator();
});

You can implement arbitrary validation with it.

您可以使用它实现任意验证。

So your validation can be implemented through some global function

所以你的验证可以通过一些全局函数来实现

With HTML

使用 HTML

  <input type="text" class="form-control" name="captcha"
                data-bv-callback="true"
                data-bv-callback-message="Wrong answer"
                data-bv-callback-callback="specialValidation" />

with JS

用JS

 function specialValidation(value, validator) {
    // Determine the numbers which are generated in captchaOperation
    var items = $('#otherField').txt();
    return value == sum;
};

And you need to be creative with element attributes, to link related elements correctly.

并且您需要在元素属性方面发挥创意,以正确链接相关元素。

回答by BALAJI R

Use callback for custom validation you can use any validation on callback like javascript validation.Need to send false or true.

使用回调进行自定义验证,您可以对回调使用任何验证,例如 javascript 验证。需要发送 false 或 true。

pwd:
{
    validators:
    {
        notEmpty:
        {
            message: 'The password is required and cannot be empty'
        },
        callback:
        {
            message: 'The password is not valid',
            callback: function(value, validator, $field)
            {
                if (value === '')
                {
                    return true;
                }
            }
        }
    }
}

回答by Srikanth

You can do that, before calling bootstrap validation just add the data-required attribute to your input element if select has selected value otherwise don't add that attribute. Hope this'll help you.

您可以这样做,在调用引导程序验证之前,如果 select 已选择值,则只需将 data-required 属性添加到您的输入元素,否则不要添加该属性。希望这会帮助你。

回答by Pawel

回答by inaam husain

Use this following code, onchangejquery function is used for this.

使用以下代码, onchangejquery 函数用于此。

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>change demo</title>
  <style>
  div {
    color: red;
  }
  </style>
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<select name="sweets" multiple="multiple">
  <option>Chocolate</option>
  <option selected="selected">Candy</option>
  <option>Taffy</option>
  <option selected="selected">Caramel</option>
  <option>Fudge</option>
  <option>Cookie</option>
</select>
<div></div>

<script>
$( "select" )
  .change(function () {
    var str = "";
    $( "select option:selected" ).each(function() {
      str += $( this ).text() + " ";
    });
    $( "div" ).text( str );
  })
  .change();
</script>

</body>
</html>