server side validation in asp.net? - asp.net

hi all as i know that asp.net provide server side validation control which has there own built-in logic, so i want to ask here can we extend built-in logic, i means suppose we use compare validator for comparing two file at this point it will validate according to there built-in logic, but i want to add some code for compare validator, is this possible.
According to my knowledge in asp.net every control treated as class which has data and code so according to inheritance or extend can we add some code in validation control ?

It looks like you need to use
CustomValidator
You can use a custom function to define when your control passes your validation. In this case could be something like this.
void ServerValidation (object source, ServerValidateEventArgs args)
{
args.IsValid = //Define your validation here
}

CustomValidator is one option. If you rather going to implement validator similar to existing one, you can simply derive from it and override all necessary methods. But the most important method you should look for is the EvaluateIsValid.
A CustomValidator is better in situations when your logic is more likely unique. In case you want to use the logic in multiple places, I would recommend to use inheritance. It allows you to encapsulate the logic in class library if you want, CustomValidator doesn't.

In your markup:
<asp:TextBox id="Text1" runat="server" />
<asp:CustomValidator id="CustomValidator1"
ControlToValidate="Text1"
Display="Static"
ErrorMessage="Not an even number!"
ForeColor="green"
Font-Names="verdana"
Font-Size="10pt"
OnServerValidate="ServerValidation"
runat="server"/>
<asp:Button id="Button1"
Text="Validate"
OnClick="ValidateBtn_OnClick"
runat="server"/>
In the server side code:
void ValidateBtn_OnClick(object sender, EventArgs e)
{
// Display whether the page passed validation.
if (Page.IsValid)
{
Message.Text = "Page is valid.";
}
else
{
Message.Text = "Page is not valid!";
}
}
void ServerValidation(object source, ServerValidateEventArgs args)
{
try
{
// Test whether the value entered into the text box is even.
int i = int.Parse(args.Value);
args.IsValid = ((i%2) == 0);
}
catch(Exception ex)
{
args.IsValid = false;
}
}
This example is a shortened version of the one found at the documentation page for CustomValidator:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx

Yes you can. Like Carlos's answer link will tell you. You can put the code in the code behind.(.cs file)

Related

asp:CustomValidator - user input is equal to a set parameter

I am not too familiar with custom validation. If you are willing to help, it is MUCH appreciated!
<asp:CustomValidator ID="valMatchUserInput" runat="server" ControlToValidate="tbUserInput" ErrorMessage="Please do something."> </asp:CustomValidator>
Basically, if the user input does not match (is not equal to) a specific parameter, I would like an error message to display, so nothing happens until the user fixes the error.
Thanks!
I will give you an example...
Let's say this is your validator:
<asp:CustomValidator ID="valMatchUserInput" runat="server" ControlToValidate="tbUserInput" ErrorMessage="Please do something." **ClientValidationFunction="Bla_ClientValidate" OnServerValidate="Bla_ServerValidate"**> </asp:CustomValidator>
You have to include a server-side validation and a client-side validation.
Code behind (server-side)
protected void Bla_ServerValidate(object source, ServerValidateEventArgs args)
{
//Compare your parameter here
}
Javascript (client-side)
function bla_ClientValidate(sender, e) {
// Compare your parameter here
}
It should work then

How can I stop refreshing the page in the else condition

My code:
protected void btnOk_Click(object sender, EventArgs e)
{
if (txtReportFavorite.Text != string.Empty)
{
//..
}
else
{
Response.Write("<script>alert('Enter Favorite name.')</script>");
// I need to prevent page refresh here.
}
}
How can I stop refreshing the page in the else condition. Thanks.
You can't.
The new page has already been requested when that code runs. If you don't do a postback, that code will never run.
If you want to do the validation without doing the postback, you should do it using client code instead.
The fact that you got to the server side means that your page has done a full cycle to the server and refreshed itself.
Unless you are calling this code with an Ajax call.
You can also achieve this by placing an AjaxUpdatePanel around your button that will simulate an Ajax call when your clients will submit your form.
in your code behind on page load put this
btnOk.Attributes.Add("onclick","return validate();");
in your aspx file have this script
function validate()
{
if(document.getElementById("txtReportFavorite").value == "";
{
alert("Enter Favorite name");
return false;
}
}
Your page is already go to the server side and it is in already postback is progressing.
you have to use client side code for preventing postback.
why not to use RequiredFieldValidator if only empty textbox need to validate?
you can do it on client side.
<asp:TextBox runat="server" id="txtReportFavorite" />
<asp:RequiredFieldValidator runat="server" id="txtReportFavorite" controltovalidate="txtName" errormessage="Enter Favorite name!" />
<br />
<asp:Button runat="server" id="btnSubmit" text="Ok" onclick="btn_Click" />
protected void btnSubmitForm_Click(object sender, EventArgs e)
{
if(Page.IsValid) //for secure validation
{
//do something
}
}
Try using RegisterScriptBlock.
ClientScript.RegisterStartupScript(this.GetType),"","$(document).ready(function(){alert('Enter Favorite name.')});",true);
If you want to perform from server-side do it like above.. Otherwise many answers already posted.
The kind of functionality you are showing can be easily achieved by using a Validator so the page won't post back.
As once it reaches the server, its really not possible to stop the refresh. Well, at least as far as I know.
-Milind

Code contracts and ASP.Net Validators

Imagine I have a method having a contract :
public void Do(string value)
{
Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(value));
MyBusiness.Handle(value);
}
This method is called from an asp.net 2.0 web site, and value is grabbed from a textbox, mandatory :
<asp:TextBox ID="txtValue" runat="server" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtValue" ErrorMessage="boom" />
<asp:Button ID="btnDo" OnClick="btnDo_Click" Text="Do" />
The code behind is classic :
protected void btnDo_Click(object source, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
Do(txtDo.Text);
}
}
This code is working, but throw code contracts warnings : Requires unproven (!string.IsNullOrEmpty(value)), which let me think (not surprisingly though) that the static checker is not smart enough to see the Page.IsValid (this would probably far more complex for the static checker to have such intelligence).
What are my options in this case ?
The option option I see is to help the static check with assume :
protected void btnDo_Click(object source, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
Contract.Assume(!string.IsNullOrEmpty(value));
Do(txtDo.Text);
}
}
This has the merit to works as expected, but the client side is noised by a lot of Contract.Assume on large project.
Any idea/suggestion ?
I think that Contract.Assume() is the right choice here. Yes it's noisy, but I don't know any better way that wouldn't complicate the issue.

Easy way to set Enable=True or False based on a property

I have an <ItemTemplate> with an asp:LinkButton in, and I want to set the property Enabled to be true or false depending on a property I Eval(), something like this
<asp:LinkButton ID="btnEdit" runat="server" Text="Edit" CommandName="Edit"
Enabled='<%# (int?)Eval("KittenFriendlyStatus") == (int)KittenEnum.Awwwww %>' />
However my syntax is completely wrong, can anyone straighten it out for me, or suggest a better way of doing this? I've never done it with C# before, only Javascript.
You cannot use data-binding syntax on server-controls. To solve this problem, you need to find an event of the template control that happens when it binds. It will depend on the control. So, let's say the template control has a ItemDataBound event that passes the object beind bound. Add an event handler like this:
public void Control1_ItemDataBound(Control sender, Object data, EventArgs args) {
sender.FindControl("btnEdit").Enabled = (int?)DataBinder.Eval(data, "KittenFriendlyStatus") == (int)KittenEnum.Awwwww;
}
should be like...
Enabled='<%# (int?)Eval("KittenFriendlyStatus") == (int)KittenEnum.Awwwww ? true : false %>'
In your instance, #Chiwee's suggestion of using the ItemDataBound event is likely what you need.
If you need to provide the ability to manage this in multiple places, you can use a property to manage things cleanly like this:
protected bool EnableEdit
{
get { return btnEdit.Enabled; }
set { btnEdit.Enabled = value; }
}
or if you need to manage multiple buttons at once:
protected bool EnableEdit
{
set
{
btn1.Enabled = value;
btn2.Enabled = value;
//...
}
}
One way I use often is a function in code-behind to set property like:
Enabled=='<%# DoEnable(Eval("KittenFriendlyStatus"))%>'
//in code-behind add this function:
public bool DoEnable(object status)
{
bool enable = //decide here
return enable;
}

How to set Page.IsValid in ASP.Net

When the page class property IsValid is read only, how can I set it using my own validation method?
So far all I've been able to do is set this property by calling Page.Validate().
How can I write my own functionality that will change the IsValid property just like Page.Validate()?
You don't set IsValid directly instead you call Validate() method of the Page object. If you have your custom validation methods then you need to use CustomValidator object and set that function in its server side validation property.
<asp:CustomValidator ID="YourValidator" runat="server" SetFocusOnError="true"
ControlToValidate="YourControl"
ClientValidationFunction="YOUR_JAVASCRIPT_FUNCTION"
OnServerValidate="YOUR_SERVER_VALIDATION_FUNCTION" Text="*" />
I know this is old, but, I needed to do something similar, basically forcing the IsValid property to false (don't ask why). Here is what I did basically (what you see here is my proof of concept):
Added this to the .aspx page:
<asp:TextBox ID="txtDummy" runat="server" Visible="false" />
<asp:RangeValidator ID="rvDummy" ControlToValidate="txtDummy" runat="server" MinimumValue="1" MaximumValue="2" />
And then I added this to the code behind:
bool makeMyPageInvalid = true;
if (makeMyPageInvalid)
txtDummy.Text = "0";
Page.Validate();
if (Page.IsValid)
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "test", "alert('valid');", true);
else
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "test", "alert('not valid');", true);
You can see that this only allows you to force the page validation to an invalid state. You can use any validator or reason to set this. Hope this helps someone!
The IsValid property is read-only because it is intended for use with server and client-side validators like the RequiredFieldValidator and RegularExpressionValidator. It's read-only because you can't force a page to be valid programmatically. "Valid" in this context means all the validators on the page evaluate to true.
If you feel like using some JavaScript you can do it in the client-side by modifying the variable Page_IsValid like this:
function pageLoad() {
Page_IsValid = false;
}
I use this just in case someone clicks the submit button w/o entering data. Then I can display an alert like this:
function valid() {
if (!Page_IsValid) {
alert("Some Questions Remain Unanswered and are Marked with a Red Asterisc. ( * )");
}
(at the beginning I thought 'who would submit a form w/o data' but sooner rather than later I realized it happens)
This is a really old question, but it came up in a search so I thought I'd add my answer to it. First, create an extension method in one of your helper classes.
public static IEnumerable<T> GetAllControlsOfType<T>(this Control parent) where T : Control
{
var result = new List<T>();
foreach (Control control in parent.Controls)
{
if (control is T)
{
result.Add((T)control);
}
if (control.HasControls())
{
result.AddRange(control.GetAllControlsOfType<T>());
}
}
return result;
}
Now in your code behind file, loop over every validator on the page that is not validating.
foreach (var validator in Page.GetAllControlsOfType<BaseValidator>().Where(w => !w.IsValid))
{
validator.IsValid = true;
}

Resources