Monday, January 12, 2015

Check Special Character in File folder name using regular expression


In Javascript:

function checkFolderName(str) {
    strreg = /^[\w\-]+$/
    var strregx = new RegExp(strreg);
    if (strregx.test(str)) {
        //alert("OK")
        return false
    }
    else {
        //alert("Not OK")
        return true
    }
}

function checkFileName(str) {
    var name = str.substr(0, str.lastIndexOf('.'));
    var ext = str.substr(str.lastIndexOf('.') + 1);
    ext = ext.toLowerCase();
    //alert(name);
    //alert(ext);
    strreg = /^(?!.*  )(?!.*__)(?!.*--)[\w -]+$/    //Check alphanumeric with underscore and Hyphan and two consecutive spaces,underscore,hyphen
    //strreg = /^[a-zA-Z0-9_\-]+$/          //Check alphanumeric with underscore and Hyphen
    var strregx = new RegExp(strreg);
    if ((strregx.test(name)) && (ext != "asp") && (ext != "aspx") && (ext != "dll") && (ext != "cmd") && (ext != "bat") && (ext != "exe")) {
        //alert("OK")
        return false
    }
    else {
        //alert("Not OK")
        return true
    }
}
//-->

How To use function:

if(checkFolderName(document.getElementById("abc").value))
{
    alert("Please don't use special char in Foldername.")
}

if(checkFileName(document.getElementById("abc").value))
{
    alert("Please don't use special char in File Name.")
}

</SCRIPT>

In VBScript
<%

function checkFoldername(Foldername)
    dim RegularExpressionObject: Set RegularExpressionObject = New RegExp
    dim matches: matches=""
    RegularExpressionObject.Pattern = "^[\w\-]+$"
    matches = RegularExpressionObject.Test(Foldername)
    checkFoldername = matches
    set RegularExpressionObject = nothing
end function
function checkFilename(Filename)
    arrFname = split(Filename,".")
    strExtNum = ubound(arrFname)
    strExt = lcase(arrFname(strExtNum))
 
    for i = 0 to ubound(arrFname)-1
        if strfilename = "" then
            strfilename = arrFname(i)
        else
            strfilename = strfilename&"."&arrFname(i)
        end if
    next
    strOK = false
    dim RegularExpressionObject: Set RegularExpressionObject = New RegExp
    dim matches: matches=""
    'RegularExpressionObject.Pattern = "^[\w\-]+$"
    RegularExpressionObject.Pattern = "^(?!.*  )(?!.*__)(?!.*--)[\w -]+$"
    matches = RegularExpressionObject.Test(strfilename)
    if matches and strExt<>"asp"  and strExt<>"aspx" and strExt<>"dll" and strExt<>"cmd" and strExt<>"bat" and strExt<>"exe" then
        strOK = true
    else
        strOK = false
    end if
    checkFilename = strOK
    set RegularExpressionObject = nothing
end function

function checkUploadFilename(Filename)
    arrFnameS = split(Filename,"\")
    strfnameNum = ubound(arrFnameS)
    arrFname = split(arrFnameS(strfnameNum),".")
    strExtNum = ubound(arrFname)
    strExt = lcase(arrFname(strExtNum))
 
    for i = 0 to ubound(arrFname)-1
        if strfilename = "" then
            strfilename = arrFname(i)
        else
            strfilename = strfilename&"."&arrFname(i)
        end if
    next
    strOK = false
    dim RegularExpressionObject: Set RegularExpressionObject = New RegExp
    dim matches: matches=""
    'RegularExpressionObject.Pattern = "^[\w\-]+$"
    RegularExpressionObject.Pattern = "^(?!.*  )(?!.*__)(?!.*--)[\w -]+$"
    matches = RegularExpressionObject.Test(strfilename)
    if matches and strExt<>"asp"  and strExt<>"aspx" and strExt<>"dll" and strExt<>"cmd" and strExt<>"bat" and strExt<>"exe" then
        strOK = false
    else
        strOK = true
    end if
    checkUploadFilename = strOK
    set RegularExpressionObject = nothing
end function

%>


Thursday, January 8, 2015

Textbox autocomplete using jquery in asp .net

In this asp net tutorial we will learn how to use Jquery Autocomplete. Jquery Autocomplete is a very useful plugin which allows users to quickly search and select from list of values when they type into texbox control.
Whenever user starts typing in Autocomplete enabled textbox he will see a list of suggestions based on the characters he has typed in the textbox. After getting the desired result user can select required value from the autocomplete list which will displayed in the textbox.
   
You can provide static values in the form of array or you can also bind Jquery Autocomplete with database. In this tutorial we will bind our Jquery Autocomplete plugin with database. I will use northwind database for the demonstration purpose you can choose your own database. 

Lets get started with sample application: 
Step1: Create a new asp .net website.
Step2: Create a default.aspx page and create a textbox control in it.

<asp:textbox runat="server" id="txtAutoComplete" cssclass="autosuggest"></asp:textbox>

Step3:  Add neccessary Jquery and Css files. Here I am using CDN(Content Delivery Network) for Jquery and CSS files. You can use CDN or you can download files from Jquery website to your project. Put this code between “Head” tag.


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>

Step4: Write a method to get list of employees from database and return to Jquery Autocomplete. For this example I am using WebMethod to get and return list of employees from Northwind database.
Add Connection String:
<connectionstrings>      <add name="myConnection" connectionstring="Data Source=Sqlservername;user id=sa;password=yourpassword;Initial Catalog=Northwind"></add>  </connectionstrings>
Add following namespaces:

using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
Create Following method in Default.aspx.cs page:

[WebMethod]
    public static List<string> getCustomerNames(string prefixText)
    {
        List<string> customers = new List<string>();
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select contactName As Name  from Customers where " +
                "contactName like @SearchText + '%'";
                cmd.Parameters.AddWithValue("@SearchText", prefixText);
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        customers.Add(dr["Name"].ToString());
                    }
                }
                conn.Close();
            }
        }
        return customers;
    }</string></string></string>
Step5:  Call Webmethod using Jquery and bind values for Jquery Autocomplete.Put this code between your page’s head tag.
<script type="text/javascript">
       $(document).ready(function () {
           SearchText();
       });
       function SearchText() {
           $(".autosuggest").autocomplete({
               source: function (request, response) {
                   $.ajax({
                       type: "POST",
                       contentType: "application/json; charset=utf-8",
                       url: "Default.aspx/getCustomerNames",
                       data: "{'prefixText':'" + document.getElementById('txtAutoComplete').value + "'}",
                       dataType: "json",
                       success: function (data) {
                           response(data.d);
                       },
                       error: function (result) {
                           alert("Error");
                       }
                   });
               }
           });
       }
   </script>

How to check if multiple textbox have same value?

//First get the counting of textbox
             flag = false;
             cnt =0
            $(".dyntxt").each(function () {
                if ($(this).val() == "") {
                    flag = true;
                    $(this).focus();
                    return false;
                }
            cnt =cnt +1
            });
//To Check Textbox is fiiled or not
            if (flag) {
                alert("Please fill student name")
                return false;
            }
            else if (!flag) {
                count = Number(cnt - 1);
               //count = Number((document.frmDefineSSS.cboTeamSize.selectedIndex) - 1);
                flagSame = false;
//to check the duplicate value
                for (i = 1; i <= count; i++) {
                    for (j = i + 1; j <= count + 1; j++) {

                        if ($("#txtStudName" + [i]).val() == $("#txtStudName" + [j]).val()) {
                            alert("Team Member can't be same.");
                            $("#txtStudName" + [i]).css("background-color", "yellow");
                            $("#txtStudName" + [j]).css("background-color", "yellow");
                            flagSame = false;
                            return false;

                        }
                        else {
                            $("#txtStudName" + [i]).css("background-color", "white");
                            $("#txtStudName" + [j]).css("background-color", "white");
                            flagSame = true;
                        }
                    }
                }
            }
            if(flagSame) {
                document.frm.action = ""
                document.frm.submit()
                return true
            }