Pages

Search Code Shode

Loading...

Wednesday, July 21, 2010

Validating/Masking Numbers In TextBox using Regular Expression Validator and Javascript

It wont allow spaces before or after the digits but it wont if there are only spaces so you need RequiredFieldValidator too
the RegularExpressionValidator to validate the only number without using JavaScript. So something like this:


<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TextBox1"
    ValidationExpression="\d+" Display="Static" EnableClientScript="true" ErrorMessage="Please enter numbers only"
    runat="server">


Where as if you want to forbid user to type, copy/paste, drag/drop any text other than numbers, or if you want extract numbers from user entered values, you can use code below:

For this example i am trying to validate user to enter age in a textbox, which should not be other than number:


<asp:TextBox ID="txtAge" MaxLength="3" onblur="extractNumber(this,2,false);"
    onkeypress="return blockNonNumbers(this, event, true, false);"
    onkeyup="extractNumber(this,2,false);" runat="server">
</asp:TextBox>
<asp:RequiredFieldValidator ControlToValidate="txtAge" ErrorMessage="Please Enter Age"
    ID="rfvtxtAge" runat="server">*
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ControlToValidate="txtAge"
    ErrorMessage="Please Enter Valid Age" ID="revtxtAge" runat="server"
    SetFocusOnError="true" ValidationExpression="^\d+$">*
</asp:RegularExpressionValidator>


Using asp:RequiredFieldValidator makes it sure that user enter some value.
Script below extract numbers / forbid user to enter non-numeric values:


<script type="text/javascript">
    function extractNumber(obj, decimalPlaces, allowNegative) {
        var temp = obj.value;

        // avoid changing things if already formatted correctly
        var reg0Str = '[0-9]*';
        if (decimalPlaces > 0) {
            reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
        } else if (decimalPlaces < 0) {
            reg0Str += '\\.?[0-9]*';
        }
        reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
        reg0Str = reg0Str + '$';
        var reg0 = new RegExp(reg0Str);
        if (reg0.test(temp)) return true;

        // first replace all non numbers
        var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
        var reg1 = new RegExp(reg1Str, 'g');
        temp = temp.replace(reg1, '');

        if (allowNegative) {
            // replace extra negative
            var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
            var reg2 = /-/g;
            temp = temp.replace(reg2, '');
            if (hasNegative) temp = '-' + temp;
        }

        if (decimalPlaces != 0) {
            var reg3 = /\./g;
            var reg3Array = reg3.exec(temp);
            if (reg3Array != null) {
                // keep only first occurrence of .
                //  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
                var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
                reg3Right = reg3Right.replace(reg3, '');
                reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
                temp = temp.substring(0, reg3Array.index) + '.' + reg3Right;
            }
        }

        obj.value = temp;
    }
    function blockNonNumbers(obj, e, allowDecimal, allowNegative) {
        var key;
        var isCtrl = false;
        var keychar;
        var reg;

        if (window.event) {
            key = e.keyCode;
            isCtrl = window.event.ctrlKey
        }
        else if (e.which) {
            key = e.which;
            isCtrl = e.ctrlKey;
        }

        if (isNaN(key)) return true;

        keychar = String.fromCharCode(key);

        // check for backspace or delete, or if Ctrl was pressed
        if (key == 8 || isCtrl) {
            return true;
        }

        reg = /\d/;
        var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
        var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;

        return isFirstN || isFirstD || reg.test(keychar);
    }
</script>


Hope it helps!

Happy Coding!
Happy Shoding!

Sunday, July 11, 2010

How Secure Is My Password?



HOW SECURE IS MY PASSWORD!




Type your Password




Friday, July 2, 2010

Event Delegation ASP.NET: Raise Event from User Control to Parent Page

"What is delegate?" we all have faced this question in one or more interview and the most common answer is "Function pointer". I have always been confused that what the hell are delegates? What to do with them in Web Development?? Now i came to realize the importance of delegates.

Here I am showing a simple example of delegate.
I have one user control and one aspx page. The user control contains one button. When user click on this button, I will call a method on main page using delegate.

Here is my user control:


C#
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl.ascx.cs"
    Inherits="Delegate_WebUserControl" %>
<asp:Button ID="btnTest" runat="server" Text="I am Inside User Control" OnClick="btnTest_Click" />



VB.NET

<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="WebUserControl1.ascx.vb" Inherits="Delegate_WebUserControl" %>
<asp:Button ID="btnTest" runat="server" Text="I am Inside User Control" OnClick="btnTest_Click" />


On WebUserControl.ascx.cs I have written simple delegate and event handler as shown below:

Code Behind

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Delegate_WebUserControl : System.Web.UI.UserControl
{
    // Delegate declaration 
    public delegate void OnButtonClick(string strValue);
    // Event declaration 
    public event OnButtonClick btnHandler;
    // Page load 
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnTest_Click(object sender, EventArgs e)
    {
        // Check if event is null 
        if (btnHandler != null)
            btnHandler(string.Empty);
        // Write some text to output 
        Response.Write("User Control’s Button Click <BR/>");
    }
}


Thursday, July 1, 2010

Automatically Refresh User Session Using jQuery ASP.NET - Behind the Scenes

Incredibly simple script will keep your user's session alive without any worries

Now this is something that may or may not be useful to a lot of people, depending on your situation, you may want the user to elect to refresh their Session or not (like banks usually do); but this is for applications that may have a lot of idle time and users are annoyed with their Sessions dying... considering most users don't know what a Session is, but they know that the application stops working correctly.

It uses jQuery and is incredibly simple, just a few lines of code, and no screen flicker or any annoyance to the user at all; ignorance is bliss.

First I include the following in the code-behind in any page you need to keep refreshed (works on masterpages as well):

code-behind


C#

protected int timeout;
protected void Page_Load(object sender, EventArgs e)
{
    // one minute prior to timeout (milliseconds)
    timeout = (Session.Timeout * 60000) - 60000;

VB.NET


Protected timeout As Integer
Protected Sub Page_Load(sender As Object, e As EventArgs)
    ' one minute prior to timeout (milliseconds)
    timeout = (Session.Timeout * 60000) - 60000
End Sub


Then add this jQuery to your script:

aspx or master page:
var to;
$().ready(function()
{
    to = setTimeout("TimedOut()",);
});

function TimedOut()
{
    $.post( "refresh_session.aspx", null,
    function(data)
    {
        if(data == "success")
        {
            to = setTimeout("TimedOut()", );
        }
        else
        {
            $("#timeout").slideDown('fast');
        }
    });
}

Create Edit Word Document using C# VB.NET

Here I am going to demonstrate How to Create and Edit MS Word Document  using C# and VB.NET


To create or edit MS Word document, first of all we need to add two references to our project.
  • Microsoft.Office.Core
  • Microsoft.Office.Interop.Word


اشتہارات