19

I have a view which requires that the user enter their birthdate into a textbox.

I am using the mask directive from UI-Utils.

My view has this input element in it:

<input ui-mask="99/99/9999" placeholder="MM/DD/YYYY" type="text" name="uBirthdate" ng-model="user.birthdate" required/>

and in my controller I have the scope set up as

myApp.controller('HomeCtrl', function ($scope, myService){

    $scope.user = registerService.getCurrentUser();

    $scope.submit = function () {
        //do something with $scope.user.birthdate
    };

    }
});

My issue is that in my controller, the birthdate property contains the value from the input WITHOUT the masking characters so an input of

11/20/1980 in the view becomes 11201980 as a property on the $scope

How can I make sure I have a valid masked date to work with in my controller? Just FYI, this date will be sent as JSON in a POST request to my server.

stephen776
  • 9,134
  • 15
  • 74
  • 123

3 Answers3

45

Upgrade to the lastest angular-ui and use the following syntax

ui-mask="99/99/9999" model-view-value="true"

The model-view-value will keep the mask on your model object.

map7
  • 5,096
  • 6
  • 65
  • 128
  • Is there any way for it to do 12/19/9999 so that you couldn't type in invalid dates. – Z2VvZ3Vp Aug 06 '15 at 17:18
  • I would use a client side validation library for checking valid dates instead of using the mask for this purpose – map7 Aug 07 '15 at 01:28
  • 2
    [momentjs](http://momentjs.com) can be added to check for client side validation as @map7 mentioned. – Ariful Haque Nov 17 '15 at 11:55
  • PixMach may have been looking for what I was after which is a UI mask on invalid dates that prevents invalid input. I.e. not just checking for an invalid state. The JQuery UI control at [Date mask](http://keith-wood.name/dateEntry.html) is not bad. – CYoung Sep 07 '16 at 23:31
1

try this one https://github.com/candreoliveira/ngMask help full for all mask

-2

as a string:

var string = '11201980';
var month = string.substring(0,2);
var day = string.substring(2,4);
var year = string.substring(4,8);
var birthday = month + '/' + day + '/' + year;

then, as a Date:

var birthdate = new Date(birthday);
Jake Johnson
  • 1,856
  • 1
  • 17
  • 26