2

I have a problem. I want to use a regular expression that let me introduce just numbers and "." (for decimals) on an input field, no letters and other special character.

I'm trying this:

option 1 => var restrict="[^\d+]"

option 2 => var restrict="[^\d+]"

iAttrs.restrict = ^(?![0-9]+([.]?[0-9]+))$

value.toLowerCase().replace(new RegExp(iAttrs.restrict, 'g'), '');

This regular expression is an angular directive

appModule.directive('restrict', function($parse) {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function(scope, iElement, iAttrs, controller) {
                scope.$watch(iAttrs.ngModel, function(value) {
                    if (!value) {
                        return;
                    }
                    value = value.toString();
                    $parse(iAttrs.ngModel).assign(scope, value.toLowerCase().replace(new RegExp(iAttrs.restrict, 'g'), ''));
                });
            }
        }
    });

It must remove the wrong characters written on the input. But the problem is

option 1 ==> don't let me write "." character

option 2 ==> don't let me write nothing (when I have a default value example: "300.21" that must appear on the input field ... after restrict directive finish, nothing is written on the input.

Can somebody help me?

Thanks

6
  • 1
    You need to escape dot with \. Commented Mar 5, 2015 at 14:17
  • can you be a little more explicit? , how could be the regExp ? - Please Commented Mar 5, 2015 at 14:17
  • In regex, dot represents any character. So you must escape it with \ So replace dot with \. in your regex Commented Mar 5, 2015 at 14:18
  • Can you try this regex.. /(\d*[\.])?\d+/ Commented Mar 5, 2015 at 14:18
  • No, you don't need to escape a dot that is inside square brackets. The fact that the dot is part of a "range" means that it is no longer interpreted as an atom. Try echo "hello" | grep '[.]' as a proof. Commented Mar 5, 2015 at 14:19

2 Answers 2

1

Updated based on comments:

As the case for decimal point is very particular, I created a new directive for that.

Directive Code:

angular.module("app",[]).directive('allowOnlyDecimal', function($parse) {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function(scope, iElement, iAttrs, controller) {
                // used to find out if more than one . is available 
                function nth_ocurrence(str, needle, nth) {
                  for (i=0;i<str.length;i++) {
                    if (str.charAt(i) == needle) {
                      if (!--nth) {
                         return i;    
                      }
                    }
                  }
                  return false;
                }

                scope.$watch(iAttrs.ngModel, function(value) {
                    if (!value) {
                        return;
                    }
                    value = value.toString();
                    var temp = value.replace(/[^(\d\.)]/gi, '');
                    // this removes any special character and alphabets
                    if(nth_ocurrence(temp,".",2)) {
                      temp = temp.substr(0, nth_ocurrence(temp,".",2));
                      // removes if user enters more than one decimal point
                    }
                    scope[iAttrs.ngModel] = temp;
                });
            }
        };
}).controller("MainController", function($scope) {
       $scope.someInput = 100.400;
});

In your HTML:

<input type="text" ng-model="someInput" allow-only-decimal>

WORKING DEMO

OLD ANSWER:

This could be more generic approach which you can use for most of the restrict functionality using regex.

HTML :

<input type="text" ng-model="someInput" restrict="[^(\d\.)]">

JS:

angular.module("app",[]).directive('restrict', function($parse, $timeout) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, iElement, iAttrs, controller) {
            scope.$watch(iAttrs.ngModel, function(value) {
                if (!value) {
                    return;
                }
            value = value.toString();
            $timeout(function() {
               scope[iAttrs.ngModel] = value.replace(new RegExp(iAttrs.restrict,'gi'), '');


        },10);
            });
        }
    };
}).controller("MainController", function($scope) {
       $scope.someInput = 100.400;
});
Sign up to request clarification or add additional context in comments.

8 Comments

This example is now working at all it let you introduce text also into the input field
you are right MOHAMEDRIAS , but if you see, you can write also "$" and you can put more than one "." did you see it ? thanks
i Get the same with these regular expression [^\d+\.*\d*$], but i don't understad why it let me write more than one "." and the point is that more than one "." can no't be accepted
Updated answer now. Created a new directive for this purpose as it's a special case for decimal number alone. For other generic emails and other scenario the previous solution will work.
can you give an idea how could it be ? Thanks
|
0

You can use a simple regex like this:

^\d+\.*\d*$

Working demo

enter image description here

4 Comments

This regExp works ... but when you continue writing into the input field, and write a second "." this regular expression let write it. And the problem is that, there must not be permited write a second "." character Any other idea. Thanks
@julioVG the regex I provided you does not allow two .. I've updated my question with a working demo. I think you have missed adding something.
yes yes ... you are right, i get your regExp and test it on: regexplanet.com/advanced/javascript/index.html And it work's !!! ... but when i use it on my directive, it let me write more than one "." character. (look link of image) The error is ![valid XHTML][checkmark]. [checkmark]: postimg.org/image/3smfay55t
@julioVG the regex is good but you might need to escape the backslashes. Try using ^\\d+\\.*\\d*$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.