0

I need sample javascript code to validate the date with mm-dd-yyyy format.

1) if user enters wrong date with respect to above date format.

2) Date range validations,start date and end date range validations.

Any help on this appreciated.

Regards, Chaitu

1

2 Answers 2

1

Validating the format could be something like:

function isValidDateFormat(s) {
  return /^\d\d-\d\d-\d\d\d\d$/.test(s);
}

For date ranges, convert the string to a date object and compare it to date objects for the limits of the range.

Here's a date validation function - no need to check the format of the input, if it's wrong, the function returns false:

// Expects date in US-specific mm-dd-yyyy or 
// mm/dd/yyyy format
function isValidDate(d) {
  var bits = d.split(/[-/]/);
  var date = new Date(bits[2] + '/'
                    + bits[0] + '/'
                    + bits[1]);
  return date && (date.getMonth()+1) == bits[0]
              && date.getDate() == bits[1]; 
}

So now you have how to validate the format, how to validate a date and how to convert a string to a date object. Should be pretty simple to do the comparison from here.

Sign up to request clarification or add additional context in comments.

Comments

0

A detailed one, I used years back...

<script language = "Javascript">
  var dtCh= "/";
  var minYear=1900;
  var maxYear=2100;

  var isInteger = function(s){
    var i;
      for (i = 0; i < s.length; i++){   
          var c = s.charAt(i);
          if (((c < "0") || (c > "9"))) return false;
      }      
      return true;
  }

  var stripCharsInBag = function(s, bag){
    var i;
      var returnString = "";
      for (i = 0; i < s.length; i++){   
          var c = s.charAt(i);
          if (bag.indexOf(c) == -1) returnString += c;
      }
      return returnString;
  }

  var daysInFebruary = function(year){
      return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
  }

  var DaysArray = function(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
        if (i==2) {this[i] = 29}
     } 
     return this
  }

  var isDate = function(dtStr){
    var daysInMonth = DaysArray(12)
    var pos1=dtStr.indexOf(dtCh)
    var pos2=dtStr.indexOf(dtCh,pos1+1)
    var strMonth=dtStr.substring(0,pos1)
    var strDay=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 : mm/dd/yyyy")
        return false
    }
    if (strMonth.length<1 || month<1 || month>12){
        alert("Please enter a valid month")
        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 (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
        alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
        return false
    }
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
        alert("Please enter a valid date")
        return false
    }
  return true
  }

  var ValidateForm = function(){
    var dt=document.frmSample.txtDate
    if (isDate(dt.value)==false){
        dt.focus()
        return false
    }
      return true
   }

</script>

And a bit of html for demonstration:

<form method="get" onSubmit="return ValidateForm()">
  <p>Enter a Date <b>(mm/dd/yyyy)</b>: <input type="text" name="txtDate" maxlength="10" size="15"></p>
  <p><input type="submit" value="Submit"></p>
</form>

2 Comments

forgot to add <html>,<head>,<title>,<body> tag then it will be a complete page. Ready to run.
You have got to be kidding! Date validation can be done in a few lines. Convert the string to a date, test whether any two parts of the date object match any two parts of the date string (say date and month). If they do, it was a valid date. If not, it wasn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.