1

I have a vb.net project where I'm using javascript for server-side control validation.

I am registering the javascript code to validate the controls using a asp button click event. The problems is that I want to stop code execution if validation fails (indicated with an alert).

My code is below:

VB:

Protected Sub cmdSubmit_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles cmdSubmit.Click
    Dim sscript As New StringBuilder
    If (Not ClientScript.IsStartupScriptRegistered("committeeEditorValidator")) Then
        Page.ClientScript.RegisterStartupScript(Me.GetType(), "committeeEditorValidator", "committeeEditorValidator();", True)
    End If
        'Need the Sub routine to stop here if a Javascript alert is thrown.
         updateMemberInfo() 
    End Sub

Javascript:

if (document.committeeEditor.txtbAcronym.value.length < 1)
    {
        document.getElementById("hderror").value = "1"
        alert("You must provide a Committee Acronym!");
        document.committeeEditor.txtbAcronym.focus();
        return false;
    }
    document.committeeEditor.submit();
}

1 Answer 1

1

The problem here is that Javascript is executed in the browser on the client-side, not on the server. This means that by the time the Javascript runs, the VB on the server is already completely finished executing.

Your best option is to find a way to check the value while the page is being rendered. If the txtbAcronym control is created server-side by your ASP.net page (rather than dynamically created client-side by a JS script) then you can just do

If txtbAcronym.Text.Length < 1 Then
    Exit Sub
End If
updateMemberInfo() 

If not, then you need to find some other way to detect this condition ahead of time or replicate the behavior on the client-side.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.