开发者

JavaScript - Validate Date

开发者 https://www.devze.com 2022-12-12 13:54 出处:网络
I have an HTML text field. I want to validate via JavaS开发者_JAVA百科cript that the value entered is a valid date in the form of \"MM/DD/YY\" or \"MM/D/YY\" or \"MM/DD/YYYY\" or \"MM/D/YYYY\". Is the

I have an HTML text field. I want to validate via JavaS开发者_JAVA百科cript that the value entered is a valid date in the form of "MM/DD/YY" or "MM/D/YY" or "MM/DD/YYYY" or "MM/D/YYYY". Is there a function that does this?

I sort of assumed there was something like isNaN but I don't see anything. Is it true that JavaScript can't validate dates?


You could use javascript's own Date object to check the date. Since the date object allows some mucking around with the month and day values (for example March 32 would be corrected to April 1), you can just check that the date you create matches the one you put in. You could shorten this if you want, but it's longer for clarity.

function checkDate(m,d,y)
{
   try { 

      // create the date object with the values sent in (month is zero based)
      var dt = new Date(y,m-1,d,0,0,0,0);

      // get the month, day, and year from the object we just created 
      var mon = dt.getMonth() + 1;
      var day = dt.getDate();
      var yr  = dt.getYear() + 1900;

      // if they match then the date is valid
      if ( mon == m && yr == y && day == d )
         return true; 
      else
         return false;
   }
   catch(e) {
      return false;
   }
}


Is it true that JavaScript can't validate dates?

No.

Is there a function that does this?

No.

You will need to write your own validation function to parse the date format (regex comes to mind) and then determine if it is valid within your specific criteria.


Check out http://momentjs.com/. Using it, this snippet

moment(yourCandidateString, 'MM-DD-YYYY').isValid()

should do the job.


This is what I use to validate a date.

Date.parse returns NaN for invalid dates.

This supports both date-only and date+time formats.

Hope this helps.

var msg;
var str = "2013-12-04 23:10:59";
str = "2012/12/42";
var resp = Date.parse(str);
if(!isNaN(resp)) { msg='valid date'; } else { msg='invalid date'; }
console.log(msg);


If you want to venture into the realms of JQuery there are plenty of validation plugins that include date validation. This plugin is one I've used a few times and has served me well.


I use Bootstrap Datepicker. One of the options with the text box disabled should do the trick.

http://www.eyecon.ro/bootstrap-datepicker/


<input type="text" id="dateinput"/>

<script type="text/javascript">
   $(#"dateinput").datepicker({
       buttonImage: "images/calendar.png",
       dateFormat: "yyyy-MMM-dd"
   });

   function validateDate() {
       if ($(#"dateinput").val().trim() == "") {
           // Is a blank date allowed?
           return true;
       }
       var oldVal = $(#"dateinput").val();   // Current value in textbox
       // Now use jQueryUI datepicker to try and set the date with the current textbox value
       $(#"dateinput").datepicker("setDate",$(#"dateinput").val());
       // Check if the textbox value has changed
       if (oldVal != $(#"dateinput").val()) {
           // The datepicker will set something different if the date is invalid
           $(#"dateinput").val(oldVal);  // Set the textbox back to the invalid date
           alert ("date was invalid");
           return false;
       } else {
           // If nothing changed, the date must be good.
           return true;
       }
   }
</script>


There does not appear to be a build-in function which does that. However, this code is probably what you're looking for:

<script type="text/javascript">

/**--------------------------
//* Validate Date Field script- By JavaScriptKit.com
//* For this script and 100s more, visit http://www.javascriptkit.com
//* This notice must stay intact for usage
---------------------------**/

function checkdate(input){
    var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
    var returnval=false
    if (!validformat.test(input.value))
        alert("Invalid Date Format. Please correct and submit again.")
    else{ //Detailed check for valid date ranges
        var monthfield=input.value.split("/")[0]
        var dayfield=input.value.split("/")[1]
        var yearfield=input.value.split("/")[2]
        var dayobj = new Date(yearfield, monthfield-1, dayfield)
        if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
            alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
        else
            returnval=true
    }
    if (returnval==false) input.select()
    return returnval
}

</script>

Source: http://www.javascriptkit.com/script/script2/validatedate.shtml


Have you googled for something like javascript date validation? It shows up some good information, and a working code example here.


I suggest you a couple of solutions.

  1. guide the user input with a date picker. This way you can control the input format. jQueryui datepicker is a popular implementation.

  2. use a js library to manage datetime data type (not an actual datatype in Javascript!!). I suggest you date.js.


Similar to this answer, Date can be used to check if the parsed version of the string corresponds to the original date string.

> datestring_valid = "2020-02-29";
> parsed_Date = new Date(datestring_valid);
> parsed_Date.toISOString().slice(0,10) == datestring_valid;
true
> datestring_invalid = "2021-02-29";
> parsed_Date = new Date(datestring_invalid);
> parsed_Date.toISOString().slice(0,10) == datestring_invalid;
false

NB: This requires the date string to be ISO formatted.

The reason this works is, that Date parses some invalid dates into something valid as in the example above. However, supplying "2020-01-32" into Date will result in the result being "Invalid Date" that isNaN.

A function that handles all of this is the following:

function isValidDateString(datestring) {
  parsed_Date = new Date(datestring);
  return (parsed_Date.toISOString().slice(0,10) == datestring) && !isNaN(parsed_Date)
};
> isValidDateString(datestring_valid)
true
> isValidDateString(datestring_invalid)
false
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号