簡體   English   中英

使用bootstrapValidator啟用和禁用字段驗證

[英]enable and disable field validation using bootstrapValidator

所以我嘗試在線檢查幾個解決方案,但我找不到解決方案來解決我使用bootstrapvalidator啟用和禁用字段驗證的問題。

當有人輸入負數(例如-4,-100,-545等)和任何非數字的數字(例如4.4.4,4.r,4t等)時,我有一個字段應該給出錯誤。 但是我想在用戶輸入-999時設置一個不會出錯的條件。

當用戶輸入非負數和數字數字的其他數字時,代碼運行良好。 如果用戶輸入負數或非數字數字,則會顯示錯誤。 當用戶輸入-999時驗證為true(不顯示錯誤),但如果用戶將數字(-999)更改為其他數字(如負數和非數字數),我的字段驗證將停止工作(意味着不要顯示任何錯誤雖然它應該顯示)。

那么如何啟用和禁用字段驗證或設置字段驗證條件以使用bootstrapValidator解決我的問題.. ???

希望你們已經遇到過這樣的問題,我希望你能幫我解決這個難題。

你可以在這里試試: https//jsfiddle.net/os3b0dqx/看看它是如何工作的

我的template.html看起來像:

<form class="well form-horizontal" action=" " method="post" id="myform">
    <div class="form-group">
        <label class="col-xs-3 control-label">Length</label>
        <div class="col-xs-5">
            <input type="text" class="form-control" id="length" name="length" />
        </div>
    </div>
    <div class="form-group">
        <div class="col-xs-5 col-xs-offset-1">
            <button type="submit" class="btn btn-default">Submit</button>
        </div>
    </div>
</form>
<script>
    $(document).ready(function() {
        $('#myform').bootstrapValidator({
            feedbackIcons: {
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                length: {
                    validators: {
                        greaterThan: {
                            value: 0,
                            message: 'The value must be greater than or equal to zero'
                        },
                        numeric: {
                            message: 'The value is not a number',
                            thousandsSeparator: '',
                            decimalSeparator: '.'
                        },
                        notEmpty: {
                            message: 'Please fill the length'
                        }
                    }
                },
            }
        }).on('click keyup input change', '[name="length"]', function() {
            if ($(this).val() == -999) {
                $('#myform').bootstrapValidator('enableFieldValidators', 'length', false);
            } else {
                $('#myform').bootstrapValidator('validateField', 'length');
                //$('#myform').bootstrapValidator('enableFieldValidators','length',true);
                // both "validateField" and "enableFieldValidators" doesn't work for me..
            }
        });
    });

刪除事件偵聽器,並使用只允許正數和特定值的正則表達式替換前兩個規則:

$('#myform').bootstrapValidator({
  fields: {
    length: {
      validators: {
        regexp: {
          regexp: '^[+]?[0-9]+([.,][0-9]+){0,1}$|^-999$',
          message: 'The value must be a number greater than or equal to zero'
        },
        notEmpty: {
          message: 'Please fill the length'
        }
      }
    },
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM