Thursday, 17 August 2006

Only validate when visible


I hit a bit of a problem today with a ASP.NET Validator Control specifically the RequiredFieldValidator. I had a dropdown with the classic 'other' option which when selected shows a textbox for the user to specify the 'other'. I only wanted to have the RequiredFieldValidator fire when the textbox is visible!! This isn't built in with the control and it was just firing even when the textbox wasn't visible for the user to enter anything in it!! After a few hours of searching the web and going round in circles I finally came up with a solution :-)

I modified my javascript that shows/hides the textbox to include the action of disabling the validator too!! Here is my script:

// Will show/hide an object depending on a selection on a dropdown.
function ShowHideObject(dropDownID, dropDownShowString, objectToHideID, validatorToDisable)
// Get the selected text from the dropdown.
selectedText = document.getElementById(dropDownID).options[document.getElementById(dropDownID).selectedIndex].text;
// Set the object to hide to hidden.
// Disable the validator.
// Does the selected text match the supplied dropDownShowString.
if (selectedText.match(dropDownString.toString()))
// YES - The selected text matches the supplied dropDownShowString.
// Show the object and enable the validator.

I then had to check before I called Page.isValid on the sever to see if the 'other' option was selected, if not then disable the validator.

All seems to be working cooool now :-)


Dan said...

Nice catch on that one. You just saved me some serious time. Thanks!

Adi said...

Oes Tsetnoc one of the ways in which we can learn seo besides Mengembalikan Jati Diri Bangsa. By participating in the Oes Tsetnoc or Mengembalikan Jati Diri Bangsa we can improve our seo skills. To find more information about Oest Tsetnoc please visit my Oes Tsetnoc pages. And to find more information about Mengembalikan Jati Diri Bangsa please visit my Mengembalikan Jati Diri Bangsa pages. Thank you So much.