Monday, March 26, 2012

performing error check on date values entered in a textbox

If you perform "Convert. ToDateTime" to the text of a textbox, the syntax should be yyyy-mm-dd. What is the syntax for performing a checking condition (so that I can output an error note if the values in the textbox are wrong rather than the whole server error screen appearing) such that I can check that the month doesn't exceed 12 and the day doesn't exceed 31 because a code such as: label1.text = Convert.ToDateTime(textbox1.text) would produce an error if the month exceeds 12 or the day exceeds 31. Thanks for the help.Why not use one of the Validator controls? There is a DataType check that can be applied to the CompareValidator (as I recall). I am not sure what it would do with yyyy-mm-dd (unless that is the format set up in regional settings) but in a pinch, you can do a custom validator...
Use the compareValidator, and set the Type to Date (making sure you also set the 'Control to Validate' property).

If you really really really want to do it in code (which is not advisable, but I have had to do it once or twice), then here is a little function I got from somebody:


Public Function IsDateValid(ByVal strDate As String) As Boolean
Try
' attempt parse
Dim dtParsed As DateTime = DateTime.Parse(strDate)
Return True
Catch ' parse failed
End Try
Return False
End Function

IsDateValid("200323") returns false
IsDateValid("20/12/2004") returns true

Not sure if it will work with yyyy-mm-dd, but try and and let us know.

HTH

Jagdip

0 comments:

Post a Comment