1

I am using angular js and below is my code which allows only numbers separated by comma.But regex which I used allows user to enter 1,,,2.

Is there any way so that I can restrict user to enter only one comma after each number?

Plunker - http://plnkr.co/edit/g1X9ldVuH4ZewAlumM1P?p=preview

  function NumberValidator() {
    return {
        require: '?ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {
            if (!ngModelCtrl) {
                return;
            }

            ngModelCtrl.$parsers.push(function(val) {
                var clean = val.replace(/[^\d+(,\d+)*$]/g, '');
                if (val !== clean) {
                    ngModelCtrl.$setViewValue(clean);
                    ngModelCtrl.$render();
                }
                return clean;
            });

            element.bind('keypress', function(event) {
                if (event.keyCode === 32) {
                    event.preventDefault();
                }
            });
        }
    };

1 Answer 1

2

Remove the clean part and replace the if condition with,

if (!/^\d+(?:,\d+)*$/.test(val)) {

This code would test whether the given value is in 1,2,3 or 1 or 3,4 formats or not.

Example:

console.log(!/^f+$/.test('ff'))

console.log(!/^f+$/.test('df'))

Think you want something like this,

str.replace(/[^\d,]|^,+|,+$|,+(?=,)/gm, '')

PLNKR

Sign up to request clarification or add additional context in comments.

10 Comments

How this would work, as I want to restrict the users to enter numbers followed by a comma in a text box, So I am using replace function
no need for replace func.. Just check each letter (on key press) with this ^\d+(?:,\d+)*$ regex. If it's not true then show the box in red color. If it's true then show it in green color.
I don't want to change text box color. Even if user press other characters it should not be shown in text box hence i am using replace
then use a replace like str.replace(/[^\d,]/g, '') . This would replace any char but not of comma or digit with an empty string
try plnkr.co/edit/C5Mu4vMRMMo7oPSmaJTr?p=preview . It should show last comma since it won't know whether there is any continuation or line end
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.