views:

143

answers:

4

is there a way to see if a date is valid without using validators?

I can't use validators in this instance and it's a long story that is too much to type but it has to do with nested controls not being able to be found in javascript. But before i insert a date i want to make sure it is valid right before the insert. any ideas?

I'm using a maskeditor and the date could look something like this "03/__/____" and this would cause an insert problem.

+1  A: 

Are you looking for DateTime.TryParse?

DateTime dt;
bool isValid = DateTime.TryParse("03/__/____", out dt); // returns false
dtb
I believe he means client-side
Eddie Deyo
+3  A: 

On the client side, use the onBlur of the control to call a javascript function, ie.:

function makeDateValid(text)
{
   //relevent js date formatting code
   return validDateText;
}
</script>

and in your control

<asp:TextBox ID="txtDate" runat="server" 
onBlur="this.value=makeDateValid(this.value)" />

then you don't need to find the control with javascript.

You shouldn't trust that to keep your SQL safe though. You should be validating on the server side (DateTime.TryParse), and parameterizing your values.

jball
A: 

The most solid way is to use a calendar control, it stores it's result in a datetime variable which will by definition be "valid", and generates various formatted strings for any purpose.

If you need to use a an edit then an alternative to the TryParse would be to check that there are two and only two forward slashes in the string and then do a string.Split. This will give you the three elements seperately, and then validate each element (Is array[0] > 0 and < 13 is array[1] > 0 and < 29,30,31,32 as appropriate, is array[2] >= today.year and < today.year+2, etc)

This, way you can not just report an invalid date, but report which component of the date is invalid,and why. Since you will undoubtedly get specific when you reject a theoretically valid date that doesn't fit your business rules, it's better to maintain consistency with your users and be as specific as you can all the way through validation.

Ken Lange
+1  A: 

use the following javascript. You can then disable the submit button/link until validation passes.

   function checkdateformat(userinput){
      var dateformat = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
      return dateformat.test(userinput) //returns true or false depending on userinput
    }

this regex example was taken from here

Also check out these other examples/code:

http://www.the-art-of-web.com/javascript/validate-date/

http://www.rgagnon.com/jsdetails/js-0063.html

And a jQuery plugin: http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Jim Schubert
i'll give this a shotthanks
Eric