ASP.NET Single Required Field Validator for multiple fields

November 17, 2011

We often face this scenario to have one validator control (to show one error message) for a group of text-boxes.

In my case, I have a phone number field which is a combination of three independent text-boxes. And I have to validate these 3 independent text-boxes as a single unit.

Show only ONE error message if any (one or more) of the three text-boxes is empty

Solution:

I have used CustomValidator control of asp.net to achieve the result. The aspx page has the following code:

<tr>
<td>
Phone-Number
</td>
<td>
<asp:TextBox ID=”Phone1″ runat=”server” MaxLength=”3″></asp:TextBox>
-
<asp:TextBox ID=”Phone2″ runat=”server” MaxLength=”3″></asp:TextBox>
-
<asp:TextBox ID=”Phone3″ runat=”server” MaxLength=”3″></asp:TextBox>
</td>
</tr>

<tr>
<td>
&nbsp;
</td>
<td>
<asp:CustomValidator runat=”server” ID=”custValidator” ClientValidationFunction=”ClientValidate”
Display=”Dynamic” ErrorMessage=”Not a valid phone number” ForeColor=”red” Font-Name=”verdana” propertyOne=”Phone1″ propertyTwo=”Phone2″ propertyThree=”Phone3″ />
</td>
</tr>

The above code has three text-boxes (Phone1, Phone2, Phone3) and a CustomValidator control (custValidator) which has got one property “ClientValidationFunction” whose value is the name of  a javascript function which has the validation logic.

This validator also contains three custom properties (you don’t find them in intellisense; just add them) each one for specifying the each text-box id of  phone number field.

These custom properties can be accessed by the client-side validation function. So this is the way we can send custom parameters to the client-side validation function from the CustomValidator.

The below is the code for javascript function:

function ClientValidate(source, arguments) {

if (document.getElementById(source.propertyOne).value.length == 0 ||
document.getElementById(source.propertyTwo).value.length == 0 ||
document.getElementById(source.propertyThree).value.length == 0)
arguments.IsValid = false;

else
arguments.IsValid = true;
}

The above JS function accesses the custom properties (source.propertyOne) and verifies if the phone number fields contain any data and finally sets “arguments.IsValid” to true/false based on condition.

If set to false, page is not valid and will not be submitted.

VALIDATE ON TEXT CHANGE EVENTS

The above code works fine and shows error message if the phone number  field is left empty and trying to submit the form. But what we want now is that when user moves focus from any of three phone number text-boxes, validation function should be triggered and show/hide the error message accordingly. This is what happens for general RequiredFieldValidator.

To handle this scenario, we have to write one more javascript function and add one extra property to the three independent phone number text-boxes. Below is the updated code.

<asp:TextBox ID=”Phone1″ runat=”server” MaxLength=”3″ CausesValidation=”true” OnChange=”txtZipOnChange(‘custValidator’)”></asp:TextBox>
-
<asp:TextBox ID=”Phone2″ runat=”server” MaxLength=”3″ CausesValidation=”true” OnChange=”txtZipOnChange(‘custValidator’)”></asp:TextBox>
-
<asp:TextBox ID=”Phone3″ runat=”server” MaxLength=”3″ CausesValidation=”true” OnChange=”txtZipOnChange(‘custValidator’)”></asp:TextBox>

Each text-box has now got “OnChange” event with a  javscript function name as the value. So this JS function will be called everytime there is a change in any of the phone number text-box fields.

Below is the javascript function:

function txtZipOnChange(validatorId) {
var i;
for (i = 0; i < Page_Validators.length; i++) {
if (Page_Validators[i].id == validatorId)
break;
}
ValidatorValidate(Page_Validators[i], null, null);
}

If you observe the above code, I am using the asp.net framework generated function “ValidatorValidate” to trigger the validation of custom validator.

And the Page_Validators array is also generated by asp.net framework which maintains all the validators on the page. In the above JS code I am finding the correct Page_Validators entry and triggering validation of that validator.

Below are the screenshot of above example:

 

Multiple file upload control in ASP.NET using JavaScript

August 6, 2011

Recently I came across a requirement to provide an option for user to upload multiple files (One or More).

We have <asp:FileUpload> control in asp.net using which we can upload one file at a time.

By using a single <asp:FileUpload> control on aspx page and few lines of  java script I could solve the purpose.

Followed these steps to achieve the requirement:

Step 1:

Placed below code on .aspx page.

         <div>
            <span>
                <asp:FileUpload ID="FileUploadCtrl0" runat="server" />
                <br />
            </span>
            <input type="button" value="Add" onclick="AddFileUpload()" />
            <asp:Button ID="btnUpload" runat="server" Text="Upload Attachments" OnClick="btnUpload_Click" />
        </div>
  • One asp:FileUpload control is placed on the aspx page (which always appears on the page by default)
  • One HTML button (Add)  to add additional file upload controls. This is done by calling a javascript method “AddFileUpload()”
  • Finally one asp:Button to handle uploading the attached documents to target location(In my case it is file system)

Step 2:

Here is the code for “AddFileUpload()” javascript method. I am using JQuery here. So dont forget to include reference to Jquery file.

   <script type="text/javascript">
        var counter = 0;
        function AddFileUpload() {
            $('.fileUploadSpan').append(
            $('<span>').append($('<input/>').attr('type', 'file').attr('name', 'FileUploadCtrl' + ++counter).attr('id', 'FileUploadCtrl' + counter), $('<input/>').attr('type', 'button').attr('value', 'Remove').click(function () { $(this).parent().remove(); --counter; }), $('<br/>'))
            );
        }
    </script>
  • The javascript function “AddFileUpload” adds a file upload control and a remove button. Remove button is used to remove the associated file upload control.

Step 3:

Finally implement aspx.Button handler(btnUpload_Click)

        protected void btnUpload_Click(object sender, EventArgs e)
        {
                // Get the HttpFileCollection
                HttpFileCollection hfc = Request.Files;
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    if (hpf.ContentLength > 0)
                    {
                        hpf.SaveAs("C:\\Temp" + "\\" +
                          System.IO.Path.GetFileName(hpf.FileName));
                        Response.Write("File: " + hpf.FileName + " Size: " +
                            hpf.ContentLength + " Type: " + hpf.ContentType + " Uploaded Successfully");
                    }
                }
        }
Finally the output looks like this:

The output of multifile upload control

And this can still be extended to look very good by putting image buttons instead of normal buttons :)

Insert People picker value using web service in SharePoint

March 30, 2010

When you want to insert a value for people picker control using a web service, the format should be -1;#<DomainName>\<UserName>.

For ex: if “PRESS” is a domain and “SAMPATHK” is the user name then the format should be like, -1;PRESS\SAMPATHK

ClientID does not work in .js file

January 14, 2010

The ClientID property does not work in .js files. So if you want to use ClientID property in javascript so do include that script in the aspx page itself. In seperate js files ClientID does not work.

ClientID for a control inside User Control

January 14, 2010

Assume that you have a user control with ID  “Login-Control” on a page. In that login control you might be having two text boxes (TB1, TB2) and two lables (LB1, LB2) and one button(BT1). If you want to get the clientID for TB1 at the page level you can’t use like <%= TB1.ClientID %> (It does not work). Here you should go for the following statement:

Login-Control.FindControl(“TB1″).ClientID

Classes and objects in javascript

December 29, 2009

Go through the link http://livingmachines.net/tag/creating-javascript-classes-series/

and learn how to create classes and objects in Javascript.

OnPreInit Event in Page Life Cycle

December 9, 2009
  1. This event occurs only for the Page class and UserControls/MasterPages do not have this method to override.
  2. Note that PreInit() is the only event where we can set themes programmatically.

Special Case with MasterPages

  1. It is important to note that Master Page is treated like a control in the Content Pages.
  2. So if a Page has a Master Page associated with it, then the controls on the page will not be initialized and would be null in this stage. Only after the Init() event starts,
    you can access these controls directly from the page class.
  3. The reason being that all controls placed in the Content Page are within a ContentPlaceholder which is a child control of a MasterPage. Now Master Page is merged and treated like a control in the Content Pages. As I mentioned earlier, all events except the Init() and Unload() are fired from outermost to the innermost control. So PreInit() in the Page is the first event to fire but User Controls or MasterPage (which is itself a Usercontrol) do not have any PreInit event . Therefore in the Page_PreInit() method, neither the MasterPage nor any user control has been initialized and only the controls inside the Page class are set to their default values. Only after the Page_PreInit() event the Init() events of other controls fire up.

Difference between ID, UniqueID, ClientID

December 3, 2009

In this post i will explain you the difference between RegularId, clientID, uniqueID properties in ASP.NET.

Regular ID:

Its a normal id that we would be giving to each control that we add to the page.

This ID is helpful for you to refer to the control in the code-behind (aspx.cs). For coding it on server side.

Unique ID:

Its a unique id for the control across the page. For example, assume that you have a user control in which you have one label. If you have added that user control twice on to the page, for two labels in two different user controls (UC1, UC2) we have the same ID known as “Label1″. But to differentiate between those two labels, ASP.NET maintains a unique ID for each label as “UC1$Label1″ and “UC2$Label1″. So Unique ID is a hierarchically qualified name. And the same thing would be assigned to the “name” property of the corresponding HTML tag. Here in the unique id, $ (dollar) character is used to separate the parent and child id.

Client ID:

Its also similar to unique id but it separates the parent and child ids using the _ (underscore) character. Then why we have this ClientID. The reason is that it would be assigned to the “id” attribute of the corresponding HTML tag on the client side. So if you want to access the control in the java script you can make use of Client ID property of a control.
Ex:
var label = document.getElementById(‘<%= Label1.ClientID%>’);

If you have added a label control onto the page then three properties of that label like ID, UniqueID, ClientID would be having the same value “Label1″.

If you want to explore more on this : go to here

Interested in solving mathematical puzzles?

November 17, 2009

You can visit this site for good puzzles.

HeadFirst Book Collection

November 16, 2009

SQL : Download

 


Follow

Get every new post delivered to your Inbox.