User Id :    Password :      New Member   Forgot Password  
 
Various functions for validation in javascript
Description JavaScript can be used to validate data in HTML forms before sending off the content to a server.   No. of Views     2206
  Rating     0
Author Najmul Hoda   Posted On     21 Aug 2011
Tags Java Script    

Sample Code   Download Code

Introduction

Before explaining the article, I would like to thank all readers who read myarticle and voted for it. Your appreciation for my article gives me strength towrite more good articles. Hope in future I will get your valuable comments and suggestions. Now I won't waste your time and come back to the topic. I havewritten this article on ‘Validations usingJava Script’. In this article, JavaScript can be used to validate data inHTML forms before sending off the content to a server.

Form data that typically are checked by a JavaScript could be:

    * Has the user left required fields empty?
    * Has the user entered a valid e-mail address?
    * Has the user entered a valid date?
    * Has the user entered text in a numeric field?

Now let's get started with step 1.
 

 1. Required Fields
 

The function belowchecks if a required field has been left empty. If the required field is blank,an alert box alerts a message and the function returns false. If a value isentered, the function returns true
 

The entire script could look something like this:
 

function validateReq(field)
{
with (field)
  {
  if (value==null||value=="")
    {
    alert("Email should be filled out!");
        return false;
    }
  else
    {
    return true;
    }
  }
}




2. E-mail Validation

The functionbelow checks if the content has the general syntax of an email.
This means thatthe input data must contain at least an @ sign and a dot (.). Also, the @ mustnot be the first character of the email address, and the last dot must at leastbe one character after the @ sign:
 
 

function ValidateEmailId(str) {
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!filter.test(str)) {
        return false;
    }
    var len = str.length;
    var ind = str.indexOf('@');
    var str1 = str.substring(ind + 1, str.length)
    if (str1.indexOf('.') == 1) {
        alert("Please enter valid email id");
    returnfalse;
    }
    var temp = new Array();
    temp = str1.split('.');
    if (temp.length > 3) {
        alert("Please enter valid email id");
    returnfalse;
    }
    return true;
}




3. Date validation

In this function it will validate followings.
a. Is a date in validate format(dd/mm/yyyy).
b. Is month in the day and month is valid in the date suppplied.
c. Is year valid.
 
 

function IsValidDate(dtStr) {
    var daysInMonth = DaysArray(12)
    var pos1 = dtStr.indexOf(dtCh)
    var pos2 = dtStr.indexOf(dtCh, pos1 + 1)
    var strDay = dtStr.substring(0, pos1)
    var strMonth = dtStr.substring(pos1 + 1, pos2)
    var strYear = dtStr.substring(pos2 + 1)

    strYr = strYear
    if (strDay.charAt(0) == "0" && strDay.length > 1) strDay = strDay.substring(1)
    if (strMonth.charAt(0) == "0" && strMonth.length > 1) strMonth = strMonth.substring(1)
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0) == "0" && strYr.length > 1) strYr = strYr.substring(1)
    }
    month = parseInt(strMonth)
    day = parseInt(strDay)
    year = parseInt(strYr)


    if (pos1 == -1 || pos2 == -1) {
        alert("The date format should be : dd/mm/yyyy")
        return false
    }
    if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]) {
        alert("Please enter a valid day")
        return false
    }
    if (strMonth.length < 1 || month < 1 || month > 12) {
        alert("Please enter a valid month")
        return false
    }

    if (strYear.length != 4 || year == 0 || year < minYear1 || year > maxYear1) {
        alert("Please enter a valid 4 digit year between " + minYear1 + " and " + maxYear1)
        return false
    }
    if (dtStr.indexOf(dtCh, pos2 + 1) != -1) {
        alert("Please enter a valid date")
        return false
    }
    return true
}


 



function daysInFebruary(year) {
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ((!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28);
}



4. Numeric validation

Here are 2 functions to validate real values and integer values.
 

function IsNumeric(strString)
//  check for valid numeric strings
{
    var strValidChars = "0123456789.-";
    var strChar;
    var blnResult = true;

    if (strString.length == 0) return false;

    //  test strString consists of valid characters listed above
    for (i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
}



 

function isInteger(s) {
    var i;
    for (i = 0; i < s.length; i++) {
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}


 

Enjoy............

 

 

About Author

About Author He is a team lead, having 8+ years of experience. He loves writing technical article for .Net developers. Najmul Hoda
No Photo
 
Country United States
Company BirlaSoft
Home Page http://www.magixchat.com

Rate this article

Rating options from poor, fair, good, very good to excelent.  
 

Comments

   
Write your comment here.
Comment
Verification Code