0

I have a directive that validates text input with regexp. I want to forbid user from inputing space characters. The directive works great with spaces inside text, but when user enters trailing or leading spaces, validation not triggers. I know that angular auto trims text input, but I can't use ng-trim = "false" directive, because my angularjs version is 1.0.6. Is there a way to fix this?

I've tried suggestion from How to disable trimming of inputs in AngularJS? for angular 1.0.x, and it partially works - validation invokes when user pastes value, which contains trailing spaces, with "ctrl+v" or mouse, but keyboard input it still not triggering validation.

custom ngTrim directive, which partially works:

app.directive('ngTrim', function() {
    return {
        require: 'ngModel',
        priority: 300,
        link: function(scope, iElem, iAttrs, ngModel) {
            if (iAttrs.ngTrim === 'false') {
                ngModel.$parsers.unshift(function() {
                    return iElem.val();
                });
            }
        }
    }
});

1 Answer 1

0

If the only thing that you'd like to do is prohibit entering of white spaces, you could attach an input listener to the element directly and remove white spaces as they are being entered like so:

iElem.bind('input', (eventData) => {
  if (eventData.data == ' ') {
    iElem.val(iElem.val().replace(/\s/g, ''));
  }
});

http://jsfiddle.net/2n6m8gtz/

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

Comments

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.