Monday 28 October 2013

Add Textboxes Dynamically and get the values

Hello Friends,
      Sometimes we need to add the textboxes dynamically and get the values from that.

first add the code at design side.

<ul>
     <li class="websiteadd">
                        <label for="user_category">
                            Websites<sup>*</sup></label>
                        <div class="inputbox" style="width: 320px; height: 28px;">
                            <asp:TextBox ID="txtWebSite" MaxLength="50" Style="height: 28px; width:210px;" runat="server"
                                CssClass="input-text wid text txtWebSite addwebsite"></asp:TextBox>
                            <asp:Button CssClass="add-btn" ID="btnAddnewWebsite" OnClientClick="return fnAddCustomWebsite();"
                                runat="server" Text="+Add" />
                        </div>
                    </li>
                    <li class="websitedelete">
                        <asp:Panel ID="panelWebSite" CssClass="panelWebSite" runat="server" Style="margin-left: 131px;">
                        </asp:Panel>
                    </li>
                </ul>

Then add the script in the head part

<script type="text/javascript">
function fnAddCustomWebsite() {
            var web = $(".addwebsite").val();
            var re = /^(www\.)[A-Za-z0-9_-]+\.+[A-Za-z0-9.\/%&=\?_:;-]+$/;
            if (!re.test(web)) {
                alert("Please Enter valid website name.");
                return false;
            }
            else {
                AddWeb++;
                var li_Web = $("<span></span>").append($("<div style='width: 320px; height:28px;'></div>").addClass("field-wrapper inputbox").append($("<input style='width: 220px; height:28px;' />").attr({ "id": "txtnewAddWeb" + AddWeb, "text": +web, "name": "txtnewAddWeb" + AddWeb }).val(web))
            .append($("<a></a>").attr({ "href": "javascript:void(0);", "class": "delete-amt", "style": "width:50px;" }).append("Delete").click(function () {
                $(this).parent().remove();
                return false;
            })));
                $(".panelWebSite").append($(li_Web));
                $(".addwebsite").val('');
                return false;
            }
        }
</script>


Then create the method to get the values as follows

public void AddWebSites()
        {
            try
            {
                UserWebsiteService objuserwebsiteservice = new UserWebsiteService();
               
                foreach (string key in Request.Params.AllKeys)
                {
                    if (key.Contains("txtnewAddWeb"))
                    {
                        string lblnewweb = Request.Params[key].ToString();
                        GEN_UserWebSite objNewWeb = new GEN_UserWebSite();
                        objNewWeb.CreatedBy = ProjectSession.UserID;
                        objNewWeb.CreatedDate = DateTime.Now;
                        objNewWeb.WebSiteName = lblnewweb.Trim();
                        objNewWeb.UserID = ProjectSession.UserID;
                        objuserwebsiteservice.InsertGEN_UserWebSite(objNewWeb);
                       
                    }
                }
            }
            catch (Exception ex)
            {
                ErrHandler.WriteError(ex);
            }
        }


Now call this function on submit button.

Maintain Page Scrol after Postback on the page

Hello friends,

    Sometimes we need to maintain scroll position of the page after postback due to dropdown change or button click in that case follow the code.

if Dropdown Control      : onChange="ab();"
if Button Control            : onClientClick ="ab();"


next take one hidden field to maintain scrol value.

<asp:HiddenField ID="TOS" runat="server" />


put the script in the head part.

<script type="text/javascript">
        function ab() {
            $("#<%= TOS.ClientID %>").val($(window).scrollTop());
        }
        function scrol() {
            setTimeout(function () { $(window).scrollTop($("#<%= TOS.ClientID %>").val()); }, 1);
        }
</script>


finally register the scrol function in last line of the event in code behind page.

ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "JavaScript:scrol();", true); 

Friday 25 October 2013

Form Validation Using jQuery and Regular Expressions

Form Validation Using jQuery and Regular Expressions

Regular expressions offer an extremely flexible and powerful way of adding validation to your website forms. Combined with jQuery, it allows you to ensure that data sent to the server matches all of your requirements.

In this post I have included several example regular expressions that we have used in our web design projects for validating form input.

For this tutorial we assume you know how to create the HTML form and add jQuery to your site. For samples you can refer to previous posts – check passwords using jQuery, email validation using jQuery or view the demo form.

1 – Validates Numeric Characters Only
Accepts only 0 – 9
$('#TxtUpdateTime').keyup(function () {
            var val = $(this).val();
            var orignalValue = val;
            val = val.replace(/[0-9]*/g, "");
            if (val != '') {
                orignalValue = orignalValue.replace(/([^0-9].*)/g, "")
                $(this).val(orignalValue);             
            }
        });


2 - No Special Characters
Allows only letters, numbers and spaces. All other characters will return an error.

$('.keyup-characters').keyup(function() {
    $('span.error-keyup-2').remove();
    var inputVal = $(this).val();
    var characterReg = /^\s*[a-zA-Z0-9,\s]+\s*$/;
    if(!characterReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-2">No special characters allowed.</span>');
    }
});

3 – Maximum Of 8 Characters
Allows all characters up to a maximum of 8. Useful for passwords, etc. The value can easily be increased/descreased by changing the {0,8}

$('.keyup-limit-8').keyup(function() {
    $('span.error-keyup-3').remove();
    var inputVal = $(this).val();
    var characterReg = /^([a-zA-Z0-9]{0,8})$/;
    if(!characterReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-3">Maximum 8 characters.</span>');
    }
});

4 - Check Email Address Format
This is a standard regular expression, which is used to validate email addresses to ensure they follow the standard format:

$('.keyup-email').keyup(function() {
    $('span.error-keyup-7').remove();
    var inputVal = $(this).val();
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if(!emailReg.test(inputVal)) {
        $(this).after('<span class="error error-keyup-7">Invalid Email Format.</span>');
    }
});

4 - Regex for float numbers

/^[-+]?[0-9]*\.?[0-9]+$/