Everybody wants to have some easy way for form validation and
user-friendly validation message box while working on web based form
in Visual Basic .NET.
Here is a small script which will help you to put as many validation
as you want and customize your message and focus based on
validation, you are looking for.
This is based on a form that has two text boxes for submitting a
date range. I am validating through this script when the user hit
submit on the form, whether both the dates are entered or not and
also, if the first date is Monday and second date is Friday of that
week or not.
Once validation is passed, it will run through
Do_Insert()
subroutine to insert the record in database.
Private Sub
BtSubmit_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles BtSubmit.Click
Dim strValidate As String
Dim Date1 As DateTime
Dim Date2 As DateTime
Date1 = TextBox1.Text
Date2 = TextBox2.Text
If TextBox1.Text = "" Then
strValidate = "<script>"
strValidate = strValidate & "alert('You must enter Reporting Start
Date!');"
strValidate = strValidate & "document.forms[0].TextBox1.focus();"
strValidate = strValidate & "</script>"
Page.RegisterStartupScript("ClientScript", strValidate)
ElseIf TextBox2.Text = "" Then
strValidate = "<script>"
strValidate = strValidate & "alert('You must enter Reporting End
Date!');"
strValidate = strValidate & "document.forms[0].TextBox2.focus();"
strValidate = strValidate & "</script>"
Page.RegisterStartupScript("ClientScript", strValidate)
'Do_Insert1("", e)
ElseIf Date1.DayOfWeek <> 1 Then
strValidate = "<script>"
strValidate = strValidate & "alert('Start Date Should Be Monday!');"
strValidate = strValidate & "document.forms[0].TextBox1.focus();"
strValidate = strValidate & "</script>"
Page.RegisterStartupScript("ClientScript", strValidate)
ElseIf Date2 <> Date1.AddDays(4) Then
strValidate = "<script>"
strValidate = strValidate & "alert('End Date Should Be Friday of the
Start Date Week!');"
strValidate = strValidate & "document.forms[0].TextBox1.focus();"
strValidate = strValidate & "</script>"
Page.RegisterStartupScript("ClientScript", strValidate)
Else
Do_Insert("", e)
End If
End Sub
That is there is to it. Hope you will find this small piece of
script useful for your many projects.
About the Author
Sameer Lal, from Toronto, Canada, is a Project Mamangement
Professional(PMP), Certified Management Accountant (CMA) from USA
and Chartered Accountant (CA) from India. Sameer is also Certified
Excel 2000 Expert and works as a consultant with one of the leading
bank of Canada.