views:

312

answers:

4

I have a simple form containing two text boxes, I am attempting to apply some validation to the first text box using JavaScript. This is the first time I have attempted this and am having some trouble.

I have a label beside the text box stating an error, this labels visibility property is set to False. I wish the labels visibility to turn true if the text box is empty when the user loses focus.

For this I have used the onBlur option within the tags of the text box. It then calls the JavaScript function and should set the label to Visible but it does not. I have tested to see if it is entering the function by using an alert instead and that works. The problem seems to be trying to alter the visibility property of the label.

Here is the portion of my code:

The JavaScript:

function myRegEx(frm) {

    if ( boxUsername.value == "" ) {

        invalidUser.visible = True;
        return false;

    }
}    

The form:

<asp:TextBox onblur="return myRegEx(this)" id="boxUsername" runat="server" Width="200px"></asp:TextBox>

<asp:Label id="invalidUser" runat="server" visible="False" forecolor="Red" text="* Username must be alphanumeric with no special characters"></asp:Label>

Any help would be brilliant.

A: 

Hi Ronnie,

Here's another StackOverflow question that has the answer for you:

http://stackoverflow.com/questions/7773/change-visibility-of-asp-net-label-with-javascript

Ken Pespisa
Brilliant thank you Ken.
Ronnie
A: 

I suggest you use and ASP.Net Validation control, specifically the RequiredFieldValidator.

This will take care of the label for you, plus make certain the correct validation happens both client side (javascript) and server-side (vb).

Joel Coehoorn
A: 

You're using the deprecated IE-only feature that turns elements with IDs into global variables.
You should call document.getElemenntById instead.

Also, you need to use ASP.Net's generated client IDs.

Finally, to hide an element, you need to use CSS; HTML doesn't have a visible property.

For example:

document.getElementById("<%=invalidUser.ClientID %>").style.display = "none";

However, you should use ASP.Net's built-in validation feature instead.

SLaks
A: 

Why not use an ASP.NET RequiredFieldValidator like so:

<asp:TextBox onblur="return myRegEx(this)" id="boxUsername" runat="server" Width="200px"></asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="boxUsername" Display="Dynamic" ErrorMessage="Please enter a value" />

If that is too simplistic then you can use a RegularExpressionValidator:

<asp:TextBox onblur="return myRegEx(this)" id="boxUsername" runat="server" Width="200px"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Please enter alpha numeric characters." ValidationExpression="[my reg ex]" ControlToValidate="boxUsername" Display="Dynamic" />
Thomas