Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required Field Validator Not Firing

Tags:

asp.net

I'm having an issue with a standard ASP.NET page that has a TextBox and a RequiredFieldValidator. The steps to reproduce are quite simple:

  1. Place a TextBox on a page
  2. Place a RequiredFieldValidator on the page
  3. Point the RequiredFieldValidator at the TextBox
  4. Run the app
  5. Tab away from the TextBox the RequiredFieldValidator does not show
  6. Enter text, then delete the text and THEN tab away, the RequiredFieldValidator does show

The RequiredFieldValidator works fine in both cases after a postback, however it seems the client-side code isn't firing until something is entered into the textbox (and then deleted).

Does anyone have a solution to this without hacking away at JavaScript myself?

like image 623
Alistair Doulin Avatar asked Nov 04 '08 06:11

Alistair Doulin


2 Answers

Is it possible this behavior is by design to suppress the appearance of validation controls until user input?

Generally speaking, Validate() gets called whenever a control is clicked that has CausesValidation set to true, like a submit button.

In any case, a poor mans work around, you could call the page Validate() function from the Load event handler. This will make things clearer to tab happy users that they need to enter something in. E.g.

protected void Page_Load(object sender, EventArgs e)
{
    Validate();
}
like image 67
Jim Burger Avatar answered Sep 28 '22 19:09

Jim Burger


A follow-up to my previous answer:

Validation occurs in the onchange event, rather than the onblur. onchange fires when the focus is lost AND the control value has changed.

To trigger validation in the onblur event, I added the following code in the Page_Load():

ScriptManager.RegisterStartupScript(this, GetType(), "js" + myTextBox.ClientID,
  "ValidatorHookupEvent(document.getElementById(\"" + myTextBox.ClientID + 
  "\"), \"onblur\", \"ValidatorOnChange(event);\");", true);

Works in ASP.Net 2.

like image 34
devio Avatar answered Sep 28 '22 20:09

devio