Tuesday 28 July 2009

ASP.NET: How to trigger the client-side validation manually

By default the client-side validation is triggered when submitting forms using buttons. However, sometimes you may want to trigger client-side validation on your ASP page manually from custom Javascript. You can achieve that by calling Javascript validation functions provided by the ASP.Net framework directly from your custom code.

The following page source example displays a TextBox and its validation controls (RequiredFieldValidator & ValidationSummary). The validation controls have the same ValidationGroup defined, which allows us to validate different page elements independently. The page displays also a DIV element that will cause the Validation action when clicked:
<!-- Validation Summary -->
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
HeaderText="Validation errors:" ValidationGroup="Group1"/>

<!-- TextBox and its validator -->
Name: <asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Name is required" Text="*"
ControlToValidate="TextBox1" ValidationGroup="Group1"> />

<!-- Div that causes client-side validation when clicked -->
<div onclick="Validate();" >Validate Form</div>

The code above should should produce smth like that when validation is triggered:

Validation form
Now let's take a look at the custom JS code that triggers the validation. There are couple ways to do that:
  • Easy way - works for all validators from the same ValidationGroup:
    function Validate()
    // If no group name provided the whole page gets validated
  • If you want to validate only specific validators:
    function Validate()
    // Get the specific validator element
    var validator = document.getElementById('RequiredFieldValidator1');

    // Validate chosen validator

    // Update validation summary for chosen validation group

Useful links:

Friday 3 July 2009

C# - Array to Dictionary

Recently I needed to convert an Array of DictionaryEntry<object,object> items into a Dictionary<string,string> object. Here is simple code using LINQ and ToDictionary method for doing that with 1 command:
DictionaryEntry<object,object>[] props = GetSomeProperties();
Dictionary<string,string> dict =
props.ToDictionary(de => (de.Key != null) ? de.Key.ToString() :
de => (de.Value != null) ? de.Value.ToString() :

Isn't that simple? :)