Force a validation group to fail if a condition isn't met
I have a group of text boxes that have required field validation hooked up to them. Obviously they all share the same validation group name. I have a check box for terms of service that needs to be checked before clicking on the submit button actually开发者_如何学运维 does anything.
Is there some C# code that will say if this box isn't checked, fail the validation group?
Or is there a better way?
edit: I added a custom validator and used this in my code behind. Does not work.
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
if (cbxTerms.Checked)
args.IsValid = true;
}
If I were to do this, I would just use JavaScript. When the page loads, attach a client side event handler to the buttons submit. Inside the handler check to see if the checkbox is checked, if so then return true otherwise return false which should cancel the submit. If JavaScript is turned off then thats OK too because you should have some server side validation happening because people can sumbit forms in other ways as well.
You can do what you did above but with a return if not checked like that
if (!cbxTerms.Checked)
{requiredlabel.text="*";
return;}
You can set a label manually to tell the user that ths field is needed
you can even prevent postback if checkbox is not checked
Button1.Attributes["onclick"] =
"if (!$get('" + CheckBox1.ClientID + "').checked){alert('Agree with us,plz!');return false;}";
why doing all the validation stuff if it can be prevented :)
or if you thurst for forcing group to invalid tou can do it win your own validation on client side:
function myStartUpValidation(group){
var result=true;
//Page_ClientValidate(group); to validate group
for (var i = 0; i < Page_Validators.length; i++) {
if(Page_Validators[i].validationGroup==group){
try{
ValidatorValidate(Page_Validators[i]); //this forces validation in all groups
if(Page_Validators[i].isvalid==false){result=false;}
}catch(err){}
}
}
return result;
}
or an extra validator...
Scott Mitchell had an article on this. https://web.archive.org/web/20211020153238/https://www.4guysfromrolla.com/articles/121907-1.aspx https://web.archive.org/web/20210304131838/https://www.4guysfromrolla.com/articles/092006-1.aspx
I think it's a slightly different approach, but I used it a while ago to handle a similar situation and it seemed to work pretty well.
I figured out how to do it. I made a textbox, assigned a req field validator to it. Put the textbox 99999px off the screen. In my c# i said if the check box is checked, the textbox.text = ""; in the checkbox check changed event I said if the check box is checked then the textbox.text = "1";. Much easier than any other solution I could find
Edit: Better to use a hidden field.
精彩评论