Multiple Min and Max values ​​for a text field

I have a working code to enter a valid minimum and maximum value in a text box using the code below:

<input type="number" name="quantity" min="1" max="5"> 

But what about if multiple ranges are allowed? For example: In my text box, numbers from 1 to 5 and from 10 to 15 are valid, so numbers from 6-9 and 16 and above are not allowed. How to do this using javascript / jquery or angularjs?

+5
source share
5 answers

Thanks for all the answers. I tried everything, but I got it using the if / else statement.

 if (txt>=1 && txt<=5){ return true } if (txt>=10 && txt<=15){ return true } if (txt>=20 && txt<=25){ return true }else{ alert("invalid") return false } 
+1
source

You can use html5 pattern attribute

 <input type="text" name="quantity" pattern= "(1|2|3|4|5|10|11|12|13|14|15)" /> 

See here on the MDN website for more details.

+3
source

Why not just use <select> ?

 <select name="quantity"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> </select> 
0
source

try it

  <form name="form1" action=""> <input type="text" name="quantity" pattern="[1-9][0-9]{2}|1000|2[0-9]{3}|3000" /> <input type="submit" value="submit"> </form> 

https://jsfiddle.net/ecxqhjkp/1/

0
source

To separate the view from the business logic, you must use custom validators.

If you used ngForm and ngModel for an input field, for example:

 <div ng-controller="InputController as inputCtrl"> <ng-form name="testForm"> <input type="text" name="testModel" ng-model="testModel"/> </ng-form> </div> 

You can use the following controller:

 app.controller('InputController', ['$scope', function($scope) { var validator = function(modelValue, viewValue) { var isRange1To5 = modelValue >= 1 && modelValue <= 5; var isRange10To15 = modelValue >= 10 && modelValue <= 15; return isRange1To5 || isRange10To15; }; $scope.testForm.testModel.$validators['rangeValidator'] = validator; }]) 

The min / max directives (and others) do just that. They add a validator to the model - which runs every time the input changes.

See the Angular docs for the issue for more information: https://docs.angularjs.org/guide/forms#custom-validation

0
source

Source: https://habr.com/ru/post/1245370/


All Articles