0

I'm using a CustomValidator in an ASP.NET page to validate the text in a TextBox as a Date-Time. I'm expecting pretty much only one format, "MM/DD/YYYY HH:MM PM". The TextBox is usually expecting to be filled by an associated DatePicker, but the user may still freeform it if they want.

Heres' the code, which seems to work. I am looking to see if there is any better JavaScript for this purpose.

function StartDateTimeValidate(source, args)
{
    var d = Date.parse(args.Value);
    if (isNaN(d))
    {
        args.IsValid = false;
    }
}
    </script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="StartDateCalendarTextBox" runat="server" Width="200"></asp:TextBox>
<asp:CustomValidator ID="StartDateCustomValidator" runat="server" 
    ErrorMessage="Bad Date" 
    ClientValidationFunction="StartDateTimeValidate"  
    ValidateEmptyText="false" 
    ControlToValidate="StartDateCalendarTextBox"
    ></asp:CustomValidator>

1 Answer 1

1

The builtin JavaScript Date object is based upon a old Java object which is pretty limited.

A lot of projects i run into use moment.js for any date manipulation or validation.

http://momentjs.com/

If you don't want to go with moment.js, your isNaN() approach is probably the best. Otherwise you'd have to write some kind of date parsing yourself to validate the Date.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the info on moment.js. I will check it out!

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.