views:

140

answers:

2

Hi All,

I need to place some validation on an asp button to ensure it is clicked at least once.

I setup a Custom Validator, set controlToValidate as the button but then found out the Custom Validator can only validate certain controls and a button isn't one of them.

I thought about validating an invisible textbox directly next to the button but this didn't feel right. Is creating dummy controls for this sort of thing ok? Or is it bad practice? Any advice?

Thanks

+1  A: 

I will stay away from creating dummy controls. Let me ask you, why do you need to validate this? why does the user has to click on a button at least once? maybe you are using the wrong control for this, without knowing what you are trying to accomplish, I still want to suggest that you look at the possibility of using a checkbox or radio button instead. If you do, you'll have no problems using the custom validator.

However, if for some crazy reason you DO NEED to use a button and make sure the user clicks on it at least once, then just set a variable in your code and assign a value to it when the button is clicked. Check this variable's value while doing your validation... if the variable still has the default value, then it means that the user didn't click on it.

//create variable
private bool _isButtonClicked;

//set to true when user clicks
_isButtonClicked = true;

//check if it has been clicked
if(_isButtonClicked == true)

Hope this helps.

Ricardo
+1  A: 

When I use the CustomValidator control I usually use the OnServerValidate method and do my validation in the code behind.

Then, on the btnSubmit_Click I do a:

if (!IsValid) return;

this will force the browser to fire the validate method and report back to any summary controls if the validation fails.

in your cusValidator_OnServerValidate method, do you checking and then set args.IsValid = true|false depending on the results of the validation. You can also set hte error message from the OnServerValidate as well, if you're checking multiple validation rules within the same validator against the same control (ie: textbox that cannot be null but format must be a date, or something like that, you could use a requiredfieldvalidator along with in this instance as well)

Anthony Shaw