How do I get masked date in model from input in angular using ui-mask?
Asked Answered
S

3

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.

Schober answered 8/1, 2014 at 15:1 Comment(0)
P
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.

Philender answered 24/4, 2014 at 6:21 Comment(4)
Is there any way for it to do 12/19/9999 so that you couldn't type in invalid dates.Strobila
I would use a client side validation library for checking valid dates instead of using the mask for this purposePhilender
momentjs can be added to check for client side validation as @Philender mentioned.Carhart
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 is not bad.Wornout
D
1

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

Delvalle answered 2/9, 2015 at 5:5 Comment(0)
R
-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);
Raffish answered 8/1, 2014 at 15:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.