I am doing something like below on a web forms application;
protected void button_transfer_search_Click(object sender, EventArgs e) {
Page.Validate("val1");
if (!Page.IsValid && int.Parse(txtArrivalDateTrf.Text) + 5 < 10) {
return;
}
also, I have following code on my aspx file;
<div class="search-engine-validation-summary">
<asp:ValidationSummary ValidationGroup="transfer" runat="server" ShowMessageBox="false" />
</div>
my question is how to add an error message to the page before return so that validation summary can grab that and displays it. I know we can do this in mvc easily but I haven't figured out how to do that in web forms. thanks !
Whenever I find this situation this is what I do:
var val = new CustomValidator()
{
ErrorMessage = "This is my error message.",
Display = ValidatorDisplay.None,
IsValid = false,
ValidationGroup = vGroup
};
val.ServerValidate += (object source, ServerValidateEventArgs args) =>
{ args.IsValid = false; };
Page.Validators.Add(val);
And in my ASPX code I have a ValidationSummary control with a ValidationGroup set to the same value as vGroup
.
Then, after I have loaded as many CustomValidators (or any other kind of validators) by codebehind as I want I simply call
Page.Validate()
if (Page.IsValid)
{
//... set your valid code here
}
The call to Page.Validate()
calls the lambda-linked method of all code-behind inserted validators and if any returns false the page is invalid and returned with no code executed. Otherwise, the page returns a valid value, and executes the valid code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With