views:

44

answers:

4

I'm using the built-in ASP validators on a few form elements. They work fine - if I click the submit button (a Button), validation occurs without postback and errors are displayed in a ValidationSummary. When that occurs, I also want to call a method in codebehind which changes the CSS of elements, switching their background color to red to reflect errors. I've tried to call this method using both OnClick and OnClientClick in the submit Button, but neither parameter seems to fire the method - client-side validation always takes priority, and a postback never occurs. Can anyone enlighten me?

EDIT #1

Using orandovs link worked alright for changing the element itself, but how about its parent?

For example, in C# I'm doing:

foreach (BaseValidator validator in Page.Validators)
{
    Panel panel = validator.Parent as Panel;

    if (!validator.IsValid)
        panel.CssClass = "error";
    else
        panel.CssClass = "normal";
}

Is there a way to get the parent control (which are all consistently Panels, so I know CssClass will exist) using JavaScript? Something like:

 $("#" + Page_Validators[i].controltovalidate.parent).CssClass("error");
+4  A: 

If client side validation fails, there is no post back, so you have two options:

  1. Write client side javascript to do what you want to do.
  2. Set all validators to validate on the server only (Set EnableClientScript = "false") (Not recommended)

You can do an Ajax call on failed validation, but that involves client side code, so it falls under option 1.

David Stratton
Thanks, I'm trying method #1 with orandov's link, but hit a snag...editing original question to reflect.
confuzicle
+1  A: 

Why not modify the CssClass property of the object or write some javascript code using Response.Write()

Danny G
+1  A: 

Client-side validation will block a postback. There are a few ways to do this. If you truly wish for a postback to occur, you can put this inside of an update panel and force a partial postback, which would fire off your code behind. You could also perform the CSS changing in javascript, and keep everything client-side.

Aaron
+2  A: 

I assume you are using the JQuery library and you are using the javascript code from this answer.

Jquery has a parent() and an addClass() function. Documentation: parent, addClass.

Here is the modified code to set the parent element's css class:

if (!Page_Validators[i].isvalid) {
   $("#" + Page_Validators[i].controltovalidate).parent().addClass("error");
}
else{
    //Make sure you remove the error class if the error has been fixed
    $("#" + Page_Validators[i].controltovalidate).parent().removeClass("error");
}
orandov
+1. That's certainly more helpful than my answer.
David Stratton