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…

CSS Friendly Adapters and Skins

ASP.NET CSS Friendly Control Adapters
http://www.asp.net/CSSAdapters/
http://www.codeplex.com/cssfriendly

I guess this exists because Microsoft realizes that some of its rendered HTML code are not that easy to apply CSS to. So this adapter comes and stands in the way of the rendering process to generate different sets of HTML. It’s pretty cool because at the very least it exposes the way to render customized HTML based on whatever requirements.

However, I don’t find it useful for all the controls it currently supports. On the contrary, some make it even harder to apply CSS to. With the help of Skin files, the look and feel of controls such GridView or DetailsView can be pretty well customized.

As of any other MS technologies, there are always more than one way of doing it. Whatever fits your need should be used…

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.

ScrollBar styles

Apparently scroll bar styles are only supported by IE. Diddn’t realize this until today.

Regardless, I think it’s a pretty cool thing to have and Firefox and Safari will eventually adopt it. Here’s a site to generate the CSS codes. It’s pretty darn good…

http://www.spectrum-research.com/V2/projects_scrollbar_generator.asp

http://www.spectrum-research.com/V2/generators/scrollbar.asp

CSS CSS CSS

Don’t know how to make your website pretty? Nothing new, it’s always a struggle… TURN FOR HELP AND LEARN!

WebDesignerWall – This site is just GOD LIKE. It’s beyond awesomeness!! Don’t know how? LEARN!!

Below are several other misc sites, none has tutorials except the first couple, but one of the best ways, and the first step, of learning how to make things pretty is to look at pretty things, isn’t it? Look at the sample works, featured sites or whatever…

N.Design Studio

BestWebGallery

FlashMint

StyleMedia

EKOnline

GraphicallySpeaking