Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: How to validate date in US format?

I have the following form code that allows input of a date using AngularUI (date is required and should match US date format e.g.: MM/DD/YY):

<form name="form" ng-submit="createShipment()">
    <!-- Shipment Date must be in MM/DD/YY format: -->  
    <input name="shipmentDate" 
          ng-pattern='/^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/'
          ui-date="{ dateFormat: 'mm/dd/y' }" required ng-model="shipment.ShipmentDate" type="text">
    <span ng-show="form.shipmentDate.$error.required">Date Required!</span>
    <span ng-show="form.shipmentDate.$error.pattern">Incorrect Format, should be MM/DD/YY!</span>

    <input class="btn-primary" ng-hide="!form.$valid" type="submit" value="Create">
</form>

Validation for required field works fine, but date format is not being validated correctly and always shows 'Incorrect Format...' message.

I tried several different Regular Expressions that worked fine elsewhere, but it is still not working. Also I tried AngularUI validation and it doesn't work either. Thanks in advance!

UPDATE:

I figured that validation was conflicting with AngularUI datepicker I used, but datepicker autocorrects date anyway, so if datepicker is not used, than validation works as long as regular expression works, and if datepicker is used, there is not much need for other validation.

like image 881
mikhail-t Avatar asked Jan 03 '13 20:01

mikhail-t


People also ask

How do you check if a date is valid?

Given date in format date, month and year in integer. The task is to find whether the date is possible on not. Valid date should range from 1/1/1800 – 31/12/9999 the dates beyond these are invalid. These dates would not only contains range of year but also all the constraints related to a calendar date.

How do you check if the date is in YYYY-MM-DD format in JavaScript?

The toISOString() method returns a string formatted as YYYY-MM-DDTHH:mm:ss. sssZ . If the ISO representation of the Date object starts with the provided string, we can conclude that the date string is valid and formatted as YYYY-MM-DD .


2 Answers

Your ng-pattern worked in a fiddle I created, but it allows for some incorrect dates, such as 0/9/1993 and 19/2/1993.

Here's a better pattern: (note, it was updated to match @WillSadler's answer)

^(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])\/((19\d{2})|([2-9]\d{3}))$

Fiddle.

like image 118
Mark Rajcok Avatar answered Oct 24 '22 22:10

Mark Rajcok


The accepted answer doesn't work for me. I changed to:

^(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])\/((19\d{2})|([2-9]\d{3}))$

Otherwise only people born after 1990 need apply!

like image 37
Will Sadler Avatar answered Oct 24 '22 22:10

Will Sadler