How would I check for a proper custom input of mm/dd/yyyy in actionscript 3?

71 views Asked by At

I have a DataField with editable="true" and format mm/dd/yyyy. Then lets say user typed in month mm section 13 which is not correct. How can I validate it as well as dd section and yyyy section and show a pop up when it's incorrect?

Here is what happening when apply button was clicked:

var newDate:Date = dfDate.selectedDate;
var month:String = (newDate.month + 1) < 10 ? "0" + (newDate.month + 1).toString() : (newDate.month + 1).toString();
var date:String = newDate.date < 10 ? "0" + newDate.date.toString() : newDate.date.toString();
var year:Number = newDate.getFullYear();
var dateString:String = month + "/" + date + "/" + year;

Button section:

<mx:FormItem id="itemDate">
    <mx:DateField id="dfDate" yearNavigationEnabled="true" editable="true"/>
</mx:FormItem>
1

There are 1 answers

0
Oleksii Dniprovskyi On

You can use just a simple regular expression

var customRegExp:RegExp = new RegExp(/(0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])[\/](19|20)\d\d/);

And then use .test function along with some formatting stuff

var fmt:DateFormatter = new DateFormatter();
fmt.formatString = "MM/DD/YYYY";

if(!customRegExp.test(fmt.format(dfDate.selectedDate)))
{
    Alert.show("Please input date in format MM/DD/YYYY");
    enableForm(true);
}

Worked for me just fine and I think will work for others as well!

Here is code all together:

var customRegExp:RegExp = new RegExp(/(0[1-9]|1[012])[\/](0[1-9]|[12][0-9]|3[01])[\/](19|20)\d\d/);

var fmt:DateFormatter = new DateFormatter();
fmt.formatString = "MM/DD/YYYY";

if(!customRegExp.test(fmt.format(dfDate.selectedDate)))
{
    Alert.show("Please input date in format MM/DD/YYYY");
    enableForm(true);
}