Tom
Tom

Reputation: 12988

Validation - change background color of the parent of invalid elements

I am using asp.net's build in validation to set required fields but rather than just displaying a message, I want to also change the background color of the invalid element's parent div.

I think I might need to use the ClientValidationFunction option, but I can't seem to get this to work.

Here's what I have so far...

<asp:TextBox runat="server" ID="myOption" />
<asp:RequiredFieldValidator runat="server" 
     ID="myOption_req" 
     ClientValidationFunction="validateMe" 
     EnableClientScript="true" 
     ControlToValidate="myOption" 
     Text="*" 
     ErrorMessage="Please fill in all required fields" />

With the following javascript:

function validateMe(){        
    alert("Hello World");      
}

I can't even get the alert to show yet, so can't move on to getting the parent element to change background color.

Upvotes: 1

Views: 449

Answers (3)

शेखर
शेखर

Reputation: 17614

Try this,

javascript

function validateMe(sender, arguments)
{
  if (arguments.Value == "hello world")
     arguments.IsValid = true;
  else
     arguments.IsValid = false;
}

Your aspx

<asp:CustomValidator color="Red" runat="server" ID="myOption_req" 
    ClientValidationFunction="validateMe" 
    EnableClientScript="true" 
    ControlToValidate="myOption" ValidateEmptyText="true"
    Text="*" 
    ErrorMessage="Please fill in all required fields" />

Upvotes: 1

Irene
Irene

Reputation: 5

ClientValidationFunction is not an attribute of the RequiredFieldValidator.

If you want some javascript to be executed, use a CustomValidator instead, as follows:

<asp:CustomValidator color="Red" runat="server" ID="myOption_req" 
    ClientValidationFunction="validateMe" 
    EnableClientScript="true" 
    ControlToValidate="myOption" ValidateEmptyText="true"
    Text="*" 
    ErrorMessage="Please fill in all required fields" />

Don't forget to add the ValidateEmptyText="true" property, otherwise the validation will be skipped if the textbox is empty.

Upvotes: 0

user1193035
user1193035

Reputation:

set color="Red" in your validation control

and change ClientValidationFunction="javascript:validateMe();" instead of ClientValidationFunction="validateMe"

<asp:RequiredFieldValidator color="Red" runat="server" 
         ID="myOption_req" 
         ClientValidationFunction="javascript:validateMe();" 
         EnableClientScript="true" 
         ControlToValidate="myOption" 
         Text="*" 
         ErrorMessage="Please fill in all required fields" />

Upvotes: 0

Related Questions