Posted By: anoshwadia on July 21st, 2011 in General
No Gravatar

Using Javascript with QuickForms for Client Side validation/events

Typically if you want to run some Javascript, you’d need to convert your QuickForm into a Custom SmartPart. However if you only have minor changes and your changes don’t warrant going through the process of converting to a Smartpart, it is possible to still implement some javascript for your form controls.


Learning by Example:

In our example we will use a text field and format it as a social security number. We’d like the behavior to be as follows:

  1. When a user enters a 9 digit number, we format it as XXX-XX-XXXX
  2. Less than 9 digits, we warn the user with a message box.
  3. If nothing is entered, we do nothing.
  4. When the user clicks on the field to edit the value, the “-” signs should be removed so the user only sees numbers.

In the background

Our QuickForm will have a Load Action with a C# Snippet Action Item. The C# Snippet will have a String variable that has all our Javascript code. After the variable is defined, we call this script by using the  ScriptManager.RegisterStartupScript method.


    1. Your form will have a text field with the id of txtSocialSecurityNo
    2. On your QuickForm properties, click on Load Actions
    3. Add a C# Snippet Action Item (Obsolete)
    4. Your code will look like this:
String myscript = "$('#" + txtSocialSecurityNo.ClientID + @"')
                        this.value = this.value.replace('-', '')
.blur (
                        var sMyValue = this.value
                        if (!sMyValue)
                        else if(sMyValue.lenth=9)
                                this.value = sMyValue.substring(0,3) + '-' +
                                        sMyValue.substring(3,2) + '-' +
                        else if(sSrc.Length < 9)
                                alert('Invalid Social Security Number!');

       //Now we register the Javascript on the page
       ScriptManager.RegisterStartupScript(this, GetType(), "RegisterDateHandler", myscript, true);
  • The last line of the javascript that comprises of );";is worth noting since its a common cause for syntax errors. Here’s the explanation of each character.
  • ) – closes the blur() function
  • ; – end of the Javascript code
  • ” – End of the C# String that’s being assigned to the myscript variable
  • ; – denotes the end of line of code (C#)
  • Now when you build and deploy your code should work client side and format/unformat the Social Security Number field.

Leave a Reply