3

I want to format the view of a text input for a Dutch zipcode, which always starts with 4 digits, and ends with 2 letters. I.e: 1234 AA. I want a text input to automatically format the data to this format.

I tried this with ui.mask, which works if you don't put in a custom-placeholder. I don't really like the placeholder ____ __, so I set up 1234 AA.

http://plnkr.co/edit/5zC2pAM4UBNC046jwQDy

This works, but it could be possible that my zipcode starts with a 1. When I try to enter my example-zipcode 1122 AB, I can't.

I also messed around with formatters and parsers, but I couldn't get it to work. The value in the model should be 1234AA, without a space.

3
  • If anyone has another solution, possibly with the formatters and parsers that would be welcome too. Commented Mar 17, 2015 at 8:40
  • In our project we use jQuery Mask which works quite well: igorescobar.github.io/jQuery-Mask-Plugin Commented Apr 17, 2015 at 9:52
  • Thanks for your effort Jürgen, but I don't want to use jQuery for this. I rewrote this part to vanilla JS. The difference is that it now only formats on blur, by just splitting the string in 2 parts using substring, and joining them back together with a space in between. Commented Apr 22, 2015 at 23:22

1 Answer 1

1

It seems that setting a placeholder in the input messes with the masking.

What you can do is create a directive to add the placeholder after ui-mask processes that there is no placeholder and uses the ui-mask's value instead:

Create this directive:

.directive("myPlaceholder",function($timeout){
    return{
        link: function(scope, element, attrs){          
          $timeout(function() {
            element.removeAttr('placeholder');
            element.attr('placeholder', attrs.myPlaceholder);
          });         

        }
    }
})

And set it into your input instead of the actual placeholder:

<input type="text" ui-mask="9999 AA" ng-model="x" my-placeholder="1234 AA" />

Check it here:

http://plnkr.co/edit/Hxj63BXDmldEpGJry8F9?p=preview

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.