Saturday 26 November 2011

How to Validate server side controls in Asp.net using Custom Validator


Some times we require that the page should not be submitted when server side control is being used.

We have two kinds of server side control validation as given below:
1). TextBox Custom Validation
2). File Upload control custom Validation


1). TextBox Custom Validation

Java Script :

function ConfirmApproval(source, args)
    {
   
  //debugger;
        var t1 = document.getElementById("TxtCurrDate").value;
        var t2 = args.Value//document.getElementById("TxtHidden").value;
        if(args.Value == t1)
            {
//            alert('hello');
//            }
                var r=confirm("The Price on this Date are already in Database, Do Your Really wants to Update !");
                if (r==true)
                  {
                        args.IsValid = true;
                        return;
//                      return true;
                  }
                else
                  {    
                        args.IsValid = false;
                        return;
//                        return false;
                  }       
        }   

    }



Custom Validator control Validation:

<asp:CustomValidator id="CheckUpdate"
        runat="server"
        ControlToValidate="TxtHidden"
        ValidateEmptyText="true"
        ClientValidationFunction="ConfirmApproval"
        Display="None">custom validator</asp:CustomValidator><br />



2). File Upload control custom Validation


Java Script :

function ValidateUpl(source, args)
    {  
        //debugger;
        var fuData = document.getElementById('<%= UplFile.ClientID %>');
        var FileUploadPath = fuData.value;

            if(FileUploadPath =='')
                {
                 alert('Please choose Excel file for update Rate list.');
                 args.IsValid = false;
                }
                 else
                {
                 var Extension = FileUploadPath.substring(FileUploadPath.lastIndexOf('.') + 1).toLowerCase();

                if (Extension == "xls")
                {
                args.IsValid = true; // Valid file type
                 }
                else
                {
                alert('Please choose Excel file for Update Rate list.');
                args.IsValid = false; // Not valid file type
                }
                }

    }


Custom Validator control Validation:

<asp:CustomValidator ID="CustomValidator1"
        runat="server"
        ClientValidationFunction="ValidateUpl"
        ControlToValidate="UplFile"
        ErrorMessage="CustomValidator" Display ="None"
        ValidateEmptyText="True"></asp:CustomValidator

No comments:

Post a Comment