0

I want to permit user to enter alphanumeric and whitespace only in this input field, but I can't seem to get it to work.

I can enter alphanumeric, but unable to enter whitespace.

I tried using /[^0-9a-zA-Z\.\\s]/g ,

/[^0-9a-zA-Z \.]/g,

/[^\w ]/g but none of them worked. Please help.

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

          ngModelCtrl.$parsers.push(function(val) {
            if (angular.isUndefined(val)) {
                var val = '';
            }
            var clean = val.replace(/[^0-9a-zA-Z\.]/g, '');
            var decimalCheck = clean.split('.');

            if(!angular.isUndefined(decimalCheck[1])) {
                decimalCheck[1] = decimalCheck[1].slice(0,2);
                clean =decimalCheck[0] + '.' + decimalCheck[1];
            }

            if (val !== clean) {
              ngModelCtrl.$setViewValue(clean);
              ngModelCtrl.$render();
            }
            return clean;
          });

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

1 Answer 1

1

To allow only alphanumeric and space.

/^[A-Za-z0-9\s]+$/m
  • ^ start
  • A-Z uppercase alphabets.
  • a-z lowercase alphabets.
  • 0-9 digits.
  • \s space
  • [A-Za-z0-9\s]+ so the above would be repeated one or more times.

To remove non-alphanumeric chars except space from the input string,

val.replace(/[^0-9a-zA-Z\s]/g, '');
Sign up to request clarification or add additional context in comments.

8 Comments

Can you please explain?
@Avinash check this line in code var clean = val.replace(/[^0-9a-zA-Z\.]/g, '');
then it would be val.replace(/[^0-9a-zA-Z\s]/g, '');
yeah.. exactly.. but /[^0-9a-zA-Z \.]/g should also work right? the one user tried!
@AvinashRaj val.replace(/[^0-9a-zA-Z\s]/g, ''); this doesn't work.
|

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.