Here is my custom Angular JS Directive to ensure user input is within the valid number range. The code works like this:

  • The user input is parsed by a regex expression to ensure that only digits are allowed.
  • Once it gets parsed, it will check if the value is within the number range specified using range-min and range-max attributes.
  • If it is below the range minimum, set the ngModel value to the range minimum value.
  • If it is more than the range maximum, set the ngModel value to the range maximum value.

Here is the Javascript code for the directive.

And here is the sample HTML code.

A good case scenario to apply this directive is for input fields for percentage where 1-100 is your number range.

This helper method checks if a given number is in between the range of the two numbers. I tried using >= and <= but they did not work. This method did the trick. I forgot where I found this one. It was in a forum about Java.

I made this method in order for me to determine if a java.util.Date falls in between 2 java.util.Date objects. I used Calendar objects to wrap the Date objects as they are much easier to use and retrieve month, day and year infos. Another helper method called isDateEqual is used within the isWithinDateRange method to determine if both Date objects are equal (excluding the time).

Related Posts Plugin for WordPress, Blogger...