ASP.NET Validation

Validation is pretty essential for a web page with form submission. But even with all the help from Microsoft’s wonderful validation controls, at times some petty details becomes quite annoying problems to solve. This post is to list out some useful resources…

Validating ASP.NET Server Controls
http://msdn.microsoft.com/en-us/library/aa479013.aspx
User Input Validation in ASP.NET
http://msdn.microsoft.com/en-us/library/ms972961.aspx
ASP.NET Validation in Depth
http://msdn.microsoft.com/en-us/library/aa479045.aspx

My own post:
CheckBox Validation

CheckBox Validation

ASP.NET provides all the wonderful validation controls and perform both client-side and server-side validation. However, to validate a CheckBox, only the Custom Validation Control can be used. Assume you have the following…

<span><asp:CheckBox ID="MyCheckBox" runat="server" onClick="if (this.checked) CheckBoxChecked(); else CheckBoxUnchecked();" />Yes, your website is awesome! =) </span>
<asp:CustomValidator ID="MyCheckBoxValidator" runat="server" ErrorMessage="Custom Validator" ClientValidationFunction="ClientValidateMyCheckBox"
    ValidationGroup="MyValidationGroup" OnServerValidate="MyCheckBoxValidator_ServerValidate">Required.</asp:CustomValidator>

Pure server-side validation will work, using the event handler MyCheckBoxValidator_ServerValidate. Here’s how it would look, and then start other methods with a check on Page.IsValid

protected void MyCheckBoxValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = (MyCheckBox.Checked);
}

On the other hand, it would be more efficient if client-side validation can also be done. The JavaScript function ClientValidateMyCheckBox is used for this purpose…

<script type="text/javascript">
function ClientValidateMyCheckBox(source, args)
{
    var cb = $get('<%=MyCheckBox.ClientID%>');
    args.IsValid = cb.checked;
}
</script>

This will trigger the client validation and if the CheckBox is unchecked, it will display the custom validator’s warning message. However, when you check the CheckBox now the validation warning message doesn’t disappear. This is because the client-side validation event is not triggerred during the client-side onClick event of the CheckBox. (Just a side-note, RequiredValidator and TextBox does not have this behavior. TextBox is validated as soon as something’s typed in.) To resolve this, a MS client-side JavaScript function needs to be hooked up with the onClick event of the CheckBox, Page_ClientValidate(“<validation group name>”) is the JS function to be used. Also note that for the “check and un-check” event of the CheckBox to work, we need to associate two functions to onClick, as shown below…

function CheckBoxChecked()
{
    var cb = $get('<%=MyCheckBox.ClientID%>');
    cb.checked = true;
    Page_ClientValidate("My_Validation_Group");
}
function CheckBoxUnchecked()
{
    var cb = $get('<%=MyCheckBox.ClientID%>');
    cb.checked = false;
    Page_ClientValidate("My_Validation_Group");
}

Final NOTE, don’t leave the validation group name out because it will then validate everything else on your page. However, do NOT use the same group name as the one you assigned in the Custom Validator also, it just doesn’t work. I can see that it doesn’t work because the ControlToValidate property is not set, so there is no linkage.

So well yeah, this will do it… of course, change accordingly if that’s not the behavior you are looking for…

Random Password Generation

Pretty cool, can be used for many purposes, like generating the decryption and validation machine keys, etc…

https://www.grc.com/passwords.htm

Select a row on GridView

There are many ways to select a row and perform whatever actions you desire in GridView. The easiest is to let its CommandField generate the select button and use the SelectedIndexChanging and SelectedIndexChanged events for the actions desired.

    <asp:CommandField ShowSelectButton="true" />

However, it would be more elegant if you can just select the row. 3 steps needed in order to achieve that:

Step 1: Add the SELECT command in RowDataBound event to each row (Assuming the ID of your GridView is “myGridView“)

    protected void PeopleGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // Just adding styles and effects
            e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
            e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";

            e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.myGridView, "Select$" + e.Row.RowIndex);
        }
    }

Step 2: Register these SELECT commands in Render to avoid the Event Validation errors

    protected override void Render(HtmlTextWriter writer)
    {
        for (int i = 0; i < this.myGridView.Rows.Count; i++)
        {
            Page.ClientScript.RegisterForEventValidation(this.myGridView.UniqueID, "Select$" + i);
        }
        base.Render(writer);
    }

Step 3: Use the SelectedIndexChanging and SelectedIndexChanged events for the actions desired

Server.HttpEncode vs. HttpUtility.HttpEncode

Just use HttpUtility.Encode because Server.HttpEncode simply calls HttpUtility.Encode. Basically if you are trying to display text back to the user and these text are either straight from database, or from databound objects, or from current page textbox entered by user, etc, use HttpUtility.Encode, mainly to prevent script-injection and handle specials characters such as blanks and punctuations, and <, >, etc…

Example:
TextBox TextBoxRoleName = (TextBox)RolesGridView.FooterRow.FindControl(“TextBoxRoleName”);
string newRoleName = TextBoxRoleName.Text.Trim();
LabelMessage.Text = “Role ‘” + Server.HtmlEncode(newRoleName) + “‘ already exists.”;

Of course, this leads to some quite important MSDN articles:

The last two articles of the above are under the following bigger, boarder title:

MSDN – .NET Security

ASP.NET AJAX username availability check

ASP.NET AJAX username availability check with UpdatePanel

ASP.NET AJAX username availability check without UpdatePanel

I used UpdatePanel in our project and it works alright. I didn’t read either of these posts when I did it. It was not too hard to figure out even though I did remember myself having some issues. However, the web service method is much much better and well worth the time to learn and implement.

Great great posts from both sites!

Modal Popup with Rounded Corners

If you set the TargetControlID of both ModalExtender and RoundedCornerExtender to one panel, ASP.NET will not like it, probably because of some JavaScript clashes.

One simply trick is to have an inner panel, surrounded by an outer panel. Set the outer panel’s background color to transparent and let the inner panel have the rounded corner extender.

Like so: (key is the transparent)
.modalPopupOuter {
background-color:Transparent;
padding:10px 10px;
width:700px;
height:520px;
}
.modalPopupInner {
background-color:#ffffff;
padding: 10px;
width:700px;
height:500px;
}

The screen shot below doesn’t have rounded corners, but it has a stand-out “X” on the top-right corner, that’s achieved by having the transparent outer panel, obviously.

Injection Attacks

ASP.NET includes a feature designed to automatically combat script injection attacks, known as request validation. Two ways to disable request validation:

  • Disable for individual page

    <%@ Page ValidateRequest="false" Language="C#" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

  • Disable the entire web application by modifying the web.config

    <configuration>
        <appSettings/>
        <connectionStrings/>
        <system.web>
          <pages validateRequest="false"/>
        </system.web>
    </configuration>

To prevent these script injection attacks, use Server.HtmlEncode:

Response.Write("Entered Input is:" + Server.HtmlEncode(txtInput.Text));

HtmlEncode replaces characters that have special meaning in HTML-to-HTML variables that represent those characters. For example, < is replaced with < and ” is replaced with “. Encoded data does not cause the browser to execute code. Instead, the data is rendered as harmless HTML.

MSDN – Providers General Overview

ASP.NET Page Info