[twitter-bootstrap] Bootstrap number validation

I'm having Bootstrap and I have problem with validation. I need input only positive integer. How to implement it?

For example:

<div>                       
    <input type="number" id="replyNumber" data-bind="value:replyNumber" />
</div>

This question is related to twitter-bootstrap

The answer is


You should use jquery validation because if you use type="number" then you can also enter "E" character in input type, which is not correct.

Solution:

HTML

<input class="form-control floatNumber" name="energy1_total_power_generated" type="text" required="" > 

JQuery

//integer value validation
$('input.floatNumber').on('input', function() {
    this.value = this.value.replace(/[^0-9.]/g,'').replace(/(\..*)\./g, '$1');
});

It's not Twitter bootstrap specific, it is a normal HTML5 component and you can specify the range with the min and max attributes (in your case only the first attribute). For example:

_x000D_
_x000D_
<div>                       _x000D_
    <input type="number" id="replyNumber" min="0" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

I'm not sure if only integers are allowed by default in the control or not, but else you can specify the step attribute:

_x000D_
_x000D_
<div>                       _x000D_
    <input type="number" id="replyNumber" min="0" step="1" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Now only numbers higher (and equal to) zero can be used and there is a step of 1, which means the values are 0, 1, 2, 3, 4, ... .

BE AWARE: Not all browsers support the HTML5 features, so it's recommended to have some kind of JavaScript fallback (and in your back-end too) if you really want to use the constraints.

For a list of browsers that support it, you can look at caniuse.com.


Well I always use the same easy way and it works for me. In your HTML keep the type as text (like this):

<input type="text" class="textfield" value="" id="onlyNumbers" name="onlyNumbers" onkeypress="return isNumber(event)" onpaste="return false;"/>

After this you only need to add a method on javascript

<script type="text/javascript">     
function isNumber(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if ( (charCode > 31 && charCode < 48) || charCode > 57) {
            return false;
        }
        return true;
    }
</script>

With this easy validation you will only get positive numbers as you wanted. You can modify the charCodes to add more valid keys to your method.

HereĀ“s the code working: Only numbers validation


you can use PATTERN:

<input class="form-control" minlength="1" pattern="[0-9]*" [(ngModel)]="value" #name="ngModel">

<div *ngIf="name.invalid && (name.dirty || name.touched)" class="text-danger">
  <div *ngIf="name.errors?.pattern">Is not a number</div>
</div>