Tuesday 18 November 2014

COMMON JAVASCRIPT VALIDATION



Hi guys, today I will create some common javascript validation function that we are using and we will use in the future. I will create one common js file every developer can use this file and please comment some more javascript validations, then I will write more validations in the js file that will help all the developers.
I have created the following validations
  1. Required Field Validation
  2. Email Validation
  3. Check for Numeric
Now JS file
function RequiredFieldValidation(id,message) {
    var value = document.getElementById(id).value;
    if (value == '') {
        alert(message);
        return false;
    }
    else {
        return true;
    }
}
function EmailValidation(id, message) {
    var mailPattern = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
    var mailID = document.getElementById(id).value;
    var matchArr = mailid.match(mailPattern);
    if (matchArr == null) {
        alert(message);
        return false;
    }
    else {
        return true;
    }
}
function CheckforNumeric(id,message) {
    var txtMin = document.getElementById(id);
    if (isNaN(txtMin.value) == true) {
        alert(message);
        txtMin.focus();
        txtMin.value = "";
        return false;
    }
    return true;
}


Now design your page to call the js file
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="Common JS File.js"></script>
    <script type="text/javascript">
        function Validation() {
          return  RequiredFieldValidation('TextBox1', 'Name Required')  
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        User Name :
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Submit" OnClientClick="return Validation()" />
   
    </div>
    </form>
</body>
</html>

No comments:

Post a Comment