Yasserzaid’s Weblog

December 26, 2009

Email Validation

Filed under: ASP.Net, Javascript — Tags: , — yasserzaid @ 8:34 pm

Hi

try this example to validate Email using Client and Server Side :-

** Using Client Side Validation **

– Example1:-

<script language="javascript" type="text/javascript">
function validateEmail()
{
var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
return regex.test(document.getElementById('<%= txtEmail.ClientID %>').value);
}
</script>

– Example2:-

<script type="text/javascript">
function validateEmail()
{
var obj=document.getElementById('<%= txtEmail.ClientID %>');
var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
if(regex.test(obj.value))
{
//You can also assign stylesheet by
//obj.className='....';
obj.style.backgroundColor = '';
obj.style.backgroundColor = '';
return true;
}
else
{
//Changing Background Color so that user can understand that its invalid
//You can also assign stylesheet by
//obj.className='....';
obj.style.backgroundColor = '#FD5E53';
obj.style.borderColor = '#CD4A4A';
return false;
}
}
</script>

and the HTML Page will be :-

<asp:TextBox ID='txtEmail' runat="server"></asp:TextBox>
<asp:Button id="cmdSave" runat="server" Text="Save" OnClientClick="return validateEmail();" />

** Using Server Side **


public static class Validation
{
public const string EmailStandard = @"^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$";
public static bool ValidateEmail(string emailID)
{
if (emailID != null)
return System.Text.RegularExpressions.Regex.IsMatch(emailID, EmailStandard);
else
return false;
}
}

Now from our aspx page write the below code when user click on a button to proceed.

if (Validation.ValidateEmail(txtEmail.Text))
{
//Valid Email
}
else
{
//Invalid Email
//Notify user
return;
}

Hope this helps

Good Luck.

December 18, 2009

AJAX HTML Editor and validation

Filed under: AJAX, ASP.Net, Javascript — yasserzaid @ 2:21 pm

Hi

try this example to validate AJAX  HTML editor :

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="TestWithValidation.aspx.vb"
    Inherits="SoluTest_HTMLEditor.TestWithValidation" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit.HTMLEditor"
    TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">
<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function test() {
            var a = $find("<%=Editor1.ClientID%>");
            var value = a.get_content();
            if (value == "") {
                $get("result").innerHTML = "Editor's content is empty";
                return false;
            }           
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <cc1:Editor ID="Editor1" runat="server" Width="300" Height="300" ValidationGroup="Editor" />
        <br />
        <span id="result"></span>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Submit" OnClientClick="return test();"
            CausesValidation="true" ValidationGroup="Editor" />
    </div>
    </form>
</body>
</html>

Hope this helps

Good Luck

December 16, 2009

Reset Controls in Web Form

Filed under: ASP.Net, Javascript — yasserzaid @ 5:39 pm

Hi

try this example to reset all controls in web page using javascript

Salient features:

  1. Using this code, you can reset HTML controls as well as ASP controls like text box, text area, radio buttons, etc.
  2. This function can reset the File Upload control as well.
  3. Using this, we can reset .NET Validation Controls too, like RequiredFieldValidater, etc.
  4. This code has no issue with any browser like FireFox, Internet Explorer, Google Chrome, Safari, etc…
<script type="text/javascript">
      
        //function for reset controls
        function ClearAllControls()
        {
            //set your validation controls prefix here.
            var validationControlsPrefix = "req";
            resetmsg(validationControlsPrefix);
              for (i=0; i<document.forms[0].length; i++)
              {
                    doc = document.forms[0].elements[i];
                    switch (doc.type)
                    {
                        case "text" :
                                doc.value = "";
                                break;
                          case "checkbox" :
                                doc.checked = false;
                                break;  
                          case "radio" :
                                doc.checked = false;
                                break;              
                          case "select-one" :
                                doc.options[doc.selectedIndex].selected = false;
                                doc.selectedIndex = 0;
                                break;                    
                          case "select-multiple" :
                                while (doc.selectedIndex != -1)
                                {
                                      indx = doc.selectedIndex;
                                      doc.options[indx].selected = false;
                                }
                                doc.selected = false;
                                break;
                         case "textarea":
                                doc.value = "";
                                break;
                          case "file" :
                              var browser=navigator.appName;
                             if(browser == 'Microsoft Internet Explorer')
                              {
                                 var fil = doc;
                                 //fil.select();
                                 n=fil.createTextRange();
                                 n.execCommand('delete');                         
                              }
                              else
                              {
                                 doc.value='';
                              }
                             break; 
                          default :
                                break;
                    }
              }
        }
      
        //function for reset validation controls
        function resetmsg(validationControlsPrefix)
        {
         
           var spans;
             var browser=navigator.appName;
             if(browser == 'Microsoft Internet Explorer')
              {
                spans = document.all.tags('span');
              }
              else
              {
                spans =  document.getElementsByTagName('span');
              }
            
            if (spans)
             {
                for (var i = 0; i < spans.length; i++)
                 {
                    var prefixLength = "" + validationControlsPrefix.length;
                    var currID = "" + spans[i].id
                    if ((currID != '') && (prefixLength != ''))
                       {
                          if (currID.substring(0,prefixLength) ==
     validationControlsPrefix)
                            {
                                spans[i].style.display = "none";
                             }
                       }
                 }
             }         
          
        }      
        </script> 

Hope  this helps

Good Luck.

December 4, 2009

AJAX Calender Date Format Validation

Filed under: AJAX, ASP.Net, Javascript — Tags: , — yasserzaid @ 11:22 am

Hi

Try this example to Validate date format with AJAX Calender Extender Control

1) Open VS 2005 and create new web site

2) Drag TextBox and AJAX Calender Control and Button control

3) Add this Javascript function to validate date format :-

function ValidateForm()
{
if(document.getElementById("txtPurchaseDate"))
{
if(validateInputDate(document.getElementById("txtPurchaseDate").value)==false)
{
alert("Please input purchase date in the format dd-mm-yyyy.");
return false;
}
}
}

//-- case 1:

//Validates date in the format dd-mm-yyyy (e.g. 19-10-2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\-.](0[1-9]1[012])[\-.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}

//-- case 2:

//Validates date in the format dd/mm/yyyy (e.g. 19/10/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\/.](0[1-9]1[012])[\/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}

//-- case 3:

//Validates date in the format dd-mm-yyyy or dd/mm/yyyy (e.g. 19-10-2009 or 19/10/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9][12][0-9]3[01])[\- \/.](0[1-9]1[012])[\- \/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}

//-- case 4:

// Validates date in the format mm/dd/yyyy (e.g. 10/19/2009)
function validateInputDate(dateString){
if (dateString.match(/^(?:(0[1-9]1[012])[\/.](0[1-9][12][0-9]3[01])[\/.](1920)[0-9]{2})$/))
{
return true;
}
else
{
return false;
}
}

//-- case 5:

// Validates date in the format yyyy-mm-dd or yyyy/mm/dd (e.g. 2009-10-19 or 2009/10/19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\- \/.](0[1-9]1[012])[\- \/.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}

//-- case 6:

// Validates date in the format yyyy-mm-dd (e.g. 2009-10-19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\-.](0[1-9]1[012])[\-.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}

//-- case 7:

// Validates date in the format yyyy/mm/dd (e.g. 2009/10/19)
function validateInputDate(dateString){
if (dateString.match(/^(?:(1920)[0-9]{2})[\/.](0[1-9]1[012])[\/.](0[1-9][12][0-9]3[01])$/))
{
return true;
}
else
{
return false;
}
}

Hope this helps

Good Luck.

November 30, 2009

Change Font Dynamically using Javascript

Filed under: ASP.Net, Javascript — yasserzaid @ 2:06 pm

Hi

you can check this previous post

Dynamic font size change using javascript

now i’m going to provide second way to change font dynamically using Javascript

Javascript Function :-

<script type="text/javascript">
    //Specify affected tags. Add or remove from list:
        var tgs = new Array( 'div','td','tr', 'p', 'span', 'font');
        //Specify spectrum of different font sizes:
        var szs = new Array( 'xx-small','x-small','small','medium','large','x-large','xx-large' );
        var startSz = 2;
        function ts( trgt,inc )
        {
         if (!document.getElementById) return
         var d = document,cEl = null,sz = startSz,i,j,cTags;
         sz += inc;
         if ( sz < 0 ) sz = 0;
         if ( sz > 6 ) sz = 6;
         startSz = sz;
         if ( !( cEl = d.getElementById( trgt ) ) ) cEl = d.getElementsByTagName( trgt )[ 0 ];
         cEl.style.fontSize = szs[ sz ];
         for ( i = 0 ; i < tgs.length ; i++ ) {
          cTags = cEl.getElementsByTagName( tgs[ i ] );
          for ( j = 0 ; j < cTags.length ; j++ ) cTags[ j ].style.fontSize = szs[ sz ];
         }
        }
    </script>

HTML Page :-

 <div style =" text-align:left; width:100%; padding:0; margin:0">
      <a href="javascript:ts('main',1)" ><img src="zoom-in.gif" alt="Zoom In" /></a> |
      <a href="javascript:ts('main',-1)"><img src="zoom-out.gif"  alt="Zoom Out" /></a>
   </div>
   <div id="dvKeys" style="display:none">
   </div>
   <div id="main">
    any text here
</div>

Hope this helps

Good Luck

November 2, 2009

Close Popup window When Press Esc Key

Filed under: ASP.Net, Javascript — Tags: — yasserzaid @ 8:17 pm

Hi

try this Example to Close Popup window When Press Esc Key using Javascript

<script type="text/javascript" language="javascript">
        function doClose(e) // note: takes the event as an arg (IE doesn't)
        {
            if (!e) e = window.event; // fix IE

            if (e.keyCode) // IE
            {
                if (e.keyCode == "27") window.close();
            }
            else if (e.charCode) // Netscape/Firefox/Opera
            {
                if (e.keyCode == "27") window.close();
            }
        }
        document.onkeypress = doClose;
</script>

Hope this helps

Good Luck

October 14, 2009

Disable and Restrict Copy Cut and Paste from on a Textbox

Filed under: ASP.Net, Javascript — yasserzaid @ 4:08 pm

Hi

try this example to Disable and Restrict Copy Cut and Paste from on a textbox using Javascript

You will need two javascript functions for this:

 

   function noCopyMouse(e) {
        var isRight = (e.button) ? (e.button == 2) : (e.which == 3);
       
        if(isRight) {
            alert('You are prompted to type this twice for a reason!');
            return false;
        }
        return true;
    }

    function noCopyKey(e) {
        var forbiddenKeys = new Array('c','x','v');
        var keyCode = (e.keyCode) ? e.keyCode : e.which;
        var isCtrl;

        if(window.event)
            isCtrl = e.ctrlKey
        else
            isCtrl = (window.Event) ? ((e.modifiers & Event.CTRL_MASK) == Event.CTRL_MASK) : false;
   
        if(isCtrl) {
            for(i = 0; i < forbiddenKeys.length; i++) {
                if(forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
                    alert('You are prompted to type this twice for a reason!');
                    return false;
                }
            }
        }
        return true;
    } 

 
And a wee bit of code-behind to handle the two events for the textbox(es):

Textbox1.Attributes.Add("onmousedown", "return noCopyMouse(event);");
 Textbox1.Attributes.Add("onkeydown", "return noCopyKey(event);");

 Hope this helps

Good Luck

October 3, 2009

Dynamic font size change using javascript

Filed under: ASP.Net, Javascript — Tags: — yasserzaid @ 3:05 pm

Hi

try this example to change font size dynamically using javascript:-

<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>" >
<head runat="server">
    <title>Change Font Size on the fly</title>
    <script type="text/javascript">
    <!--
        var min=12;
        var max=24;
        function changeFontSize(_chngValue) {
           var p = document.getElementsByTagName('p');
           for(i=0;i<p.length;i++) {
              var s =p[i].style.fontSize?parseInt(p[i].style.fontSize.replace("px","")):min;
              if(_chngValue=="higher"){
                if(s!=max)s += 1;
              }
              else if(_chngValue=="lower"){
                if(s!=min)s -= 1;
              }
              p[i].style.fontSize = s+"px";
           }
        }
    //-->
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <p>Any Test Here</p>
    <input onclick="changeFontSize('higher');" type="button" value="+"  />
    <input onclick="changeFontSize('lower');"  type="button" value="-" />
    </div>
    </form>
</body>
</html>

Hope this helps

Good Luck

Make a DropdownList visible using javasript

Filed under: ASP.Net, Javascript — yasserzaid @ 12:59 am

Hi

try this example to Make a DropdownList visible using javasript :-

<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>">
<head runat="server">
    <title>Show DDL</title>
    <script type="text/javascript">
    function showDropDown(){
        document.getElementById('<%=DropDown1.ClientID %>').style.display='block';
        document.getElementById('<%=DropDown2.ClientID %>').style.display='block';
        return false;   
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:DropDownList ID="DropDown1" runat="server" style="display:none;"></asp:DropDownList>
    <br />
    <asp:DropDownList ID="DropDown2" runat="server" style="display:none;"></asp:DropDownList>
    <br />
    <input type="button" onclick="return showDropDown();" value="ShowDDL" />
    </div>
    </form>
</body>
</html>

Hope this helps

Good Luck

October 2, 2009

Limit length of text in Gridview BoundField

Filed under: ASP.Net, Javascript — yasserzaid @ 3:48 pm

Hi

try this example to Limit length of text in BoundField :-

<script type="text/javascript"> 
function isMaxLen(o){ 
 var nMaxLen=o.getAttribute? parseInt(o.getAttribute("maxlength")):""; 
 if(o.getAttribute && o.value.length>nMaxLen){ 
 o.value=o.value.substring(0,nMaxLen) 
 } 
} 
</script>

<div>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            DeleteCommand="DELETE FROM [country] WHERE [countryid] = @countryid" InsertCommand="INSERT INTO [country]

([countryid], [countryname]) VALUES (@countryid, @countryname)"
            SelectCommand="SELECT * FROM [country]" UpdateCommand="UPDATE [country] SET [countryname] = @countryname WHERE

[countryid] = @countryid">
            <DeleteParameters>
                <asp:Parameter Name="countryid" Type="Int64" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="countryname" Type="String" />
                <asp:Parameter Name="countryid" Type="Int64" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="countryid" Type="Int64" />
                <asp:Parameter Name="countryname" Type="String" />
            </InsertParameters>
        </asp:SqlDataSource>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="countryid"
            DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:CommandField ShowEditButton="True" />
                <asp:BoundField DataField="countryid" HeaderText="countryid" ReadOnly="True" SortExpression="countryid" />
                <asp:BoundField DataField="countryname" HeaderText="countryname" SortExpression="countryname" />
            </Columns>
        </asp:GridView>
   
    </div>

and in code behind :-

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.RowState == DataControlRowState.Edit)
            {
                TextBox work =  e.Row.Cells[2].Controls[0] as TextBox;
                work.Attributes.Add("onkeydown", "isMaxLen(this)");
                work.Attributes.Add("maxlength","9");
            }
        }
    }

Hope this helps

Good Luck

Older Posts »

Blog at WordPress.com.