0

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.

Jebathon
  • 4,310
  • 14
  • 57
  • 108

1 Answers1

0

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

Community
  • 1
  • 1
mofojed
  • 1,342
  • 9
  • 11
  • Well the point was to force the validation on the user, not make a form that gives an error message if its the wrong range – Jebathon Jul 26 '15 at 21:46