Reputation: 2243
I have a Webforms aplication and don't want the user to enter invalid values.
Currently i'm solving this with validator-controls like this:
<asp:TextBox runat="server" ID="tbInsert"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ControlToValidate="tbInsert" ID="rqtbInsert"
ErrorMessage="Required">
</asp:RequiredFieldValidator>
But this validates the value just client-side (which can be avoided by the user)
Do i have to add server-side validation for each controll? What's the way it should be done?
if (!string.IsNullOrEmpty(tbInsert.Text))
{
//do sth.
}
Upvotes: 1
Views: 522
Reputation: 460108
A validator does not only check on clientside. All controls which have CausesValidation=true
will trigger Page.Validate()
on serverside which will cause all related(if ValidationGroups
are specified, otherwise all) validators to validate.
So the clientside check is optional and can be enabled/disabled via EnableClientScript
whereas the serverside check always takes place and can also be triggered programmatically with the Page.Validate
-method.
Upvotes: 5
Reputation: 325
Instead of adding the validation for each and every control. add the static validation helper class and write all the validation methods for models to the same class. just all each methods for validation from the receiving method at server end.
this way you will have dependancy saperation and achieve the desired behavour without overpopulating the method(just give a single call at the method entry)
Upvotes: 0
Reputation: 5902
At the server side, use the Page.IsValid property to check if all the validation controls passed, which returns a value indicating whether page validation succeeded. from MSDN Page.IsValid:
private void ValidateBtn_Click(Object Sender, EventArgs E)
{
Page.Validate();
if (Page.IsValid == true)
lblOutput.Text = "Page is Valid!";
else
lblOutput.Text = "Some required fields are empty.";
}
Upvotes: 1