Helpful Information
 
 
Category: ASP.NET
Javscript in codebehind page to validate textbox

I am trying to validate that a textbox is not empty using javascript.

The textbox id is txtstudycode.

Here is the codebehind code that responds to the submit link:


Private Sub lnksubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnksubmit.Click

Dim strValidateStudyName As String = "<script language='JavaScript'>" & _
"{if document.getElementById('" + txtstudycode.Text + "') = '';" & _
"alert('Study Code is Required')}</script>"

If (Not Page.IsClientScriptBlockRegistered("validateStudyName")) Then
Page.RegisterClientScriptBlock("validateStudyName", strValidateStudyName)
End If

(some other stuff down here)
End Sub

I can't get it working. I'm not using the ASP validatation controls b/c there are other buttons on the page that I don't want the validation control to respond to. But if there's any easier way by using them, I'm open to that.

I'm not using the ASP validatation controls b/c there are other buttons on the page that I don't want the validation control to respond to. But if there's any easier way by using them, I'm open to that.

I take it you are talking about other submit buttons that you do not want to trigger the validation control. If you are using Visual Studio or Web Matrix then just look at the properties of the buttons that you do not want to trigger validation. Change CausesValidation to false.

If you are not using Visual Studio or Web Matrix then add this to the asp:Button(s) that you do not want to trigger validation CausesValidation="False"

Now you can use the Validation controls

I knew there was an easier way! That works, thanks.

You are welcome. One word of warning though, make sure that the files in aspnet_client/system_web/ are up to date. The older files will cause an error, resulting in what seems like the event not firing when you click your submit button. This post on Scott Mitchell's blog (http://scottonwriting.net/sowBlog/posts/2943.aspx) explains the problem that occurs if they aren't, and also says how to fix the problem.










privacy (GDPR)