Friday, 22 April 2011

ASP: is this a date? The IsDate function


Form validation is probably the most wanted feature by web developers. Every web programmer, at least once in a lifetime, has dealt with the issue: the user fills in the form and submit wrong data. Without validation, the best thing could happen is that an error is thrown. The worst case? The wrong data is submitted to your database... and believe me, most of the time you don't want that.
While complete JavaScript form validation solutions are available everywhere, today I would like to point out that VBScript has a very simple function that can help us in checking dates at least.

The function
The function I am talking about is IsDate. I've already talked about the function in a post about SQL Server queries and date functions. The VBScript function works in a similar way.
Basically it returns a Boolean value (true/false) stating if an expression is a date or can be converted to a date. The function uses the local settings in the evaluation process, so be careful in using it: for example, English months in words are not the same in Italian.

The syntax and some examples
IsDate syntax is very basic:
Not much to say here. Expression is what we want to evaluate.
Let's see an elementary example:
Dim test_date
test_date = "22/04/2011"
response.write (IsDate(test_date))
The above snippet will output:
Dim test_date
test_date = "Hello!"
response.write (IsDate(test_date))
will return
Quite easy, isn't it?.

Why "Form validation"?
Well, it is quite clear that if we create an appropriate VBScript function, we can actually check form submission before inserting/updating data in our database.
Dim input_date
input_date = Request.Form("submitted_date")
if IsDate(input_date) = "True" then
   your submitting to database code
   response.write("Please, insert a valid date")
end if
The submitted_date is the date inserted into a form input field.

Enjoy, and let me know what you think about it in the comments section.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.