0
votes

Please see this jsFiddle (Disclaimer - the ng-keydown function isn't calling but that is not the main issue in the fiddle)

I am trying to add validation for an input box so numbers (0-100) are allowed and nothing else through a regex I made. However it is not working as expected as when using this function:

$scope.validatebox = function (e) {

        var element = e.target;
        var element_val = $(element).val();
        element_val = parseInt(element_val);

        var reg = /^[1-9][0-9]?$|^100$/;
        if (reg.test(element_val) === false) //validate
        {
            e.preventDefault();
            return;
        }

    };

The e.preventDefault() acts funny and doesn't permit the user to enter any number if there is nothing in the input box.

How can I ammend my code to force proper validation on the user so he can only enter numbers 0-100.

1
^(?:0|100|[1-9][0-9]?)$ You are missing the 0. - maraca
You parse the text into a number and then run a regex check on it - this not appropriate. - Wiktor Stribiżew
Agreed with @stribizhev also try return false; instead of just return. - maraca

1 Answers

0
votes

AngularJS has support for custom validators, and actually already has some built in for number range. Instead of writing code to work on keydown, leverage Angular's custom validators.

For numbers in particular, you can use min and max, eg:

<input type="number" name="box1" ng-model="box1"
        min="0" max="100"/>

You just need to put it in a form, and then you can display the error however you wish. Working Fiddle here: http://jsfiddle.net/js4tm3j7/1/

More info on number validators here: https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D

Info on custom validators here: https://docs.angularjs.org/guide/forms

EDIT

If you want to force validation instead of just showing an error, take a look at parsers and formatters: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

There's an example here: filters on ng-model in an input