Is this a good way to check for a valid date in JavaScript?

后端 未结 3 1270
别跟我提以往
别跟我提以往 2021-01-15 09:07

Please correct or explain how my over-simplification is incorrect as I am not a JavaScript expert.

But I just need to know if an object is a valid date. This will o

相关标签:
3条回答
  • 2021-01-15 09:40

    YOU have to decide what form of dates you want to accept.

    Then, once you know what forms you want to accept, you can then check the spec for new Date(str) or date.parse() on MDN and see if it supports exactly what you want and if it does the right things on error conditions (it probably will not). If not, then you will have to do some manual parsing.

    If you want further help from us, you will need to specify what forms of date you want to accept.

    There are also some browser differences as javascript has moved to support additional date formats and earlier browsers had some inconstencies between them which all means you'll want to build yourself a simple test script with a bunch of legal and illegal date format strings and see if your validity detection does what you want in several browsers. This isn't rocket science to get it right, but it's not trivial either and requires some work unless you only want to accept what the original date object supported (which is unlikely).

    If this were my code, I'd probably decide that it's far less work to do manual parsing of your desired input format that you know with 100% certainty will work in all browsers because it's your own manual parsing. I'd probably use a regex to parse the date and then convert each component to a number and check each component for validity. You can then feed those numeric components to the Date constructor to create the Date object.

    If you can tell by now, the built-in date class isn't very useful for user entered input. If you're willing to use a library for this, the date.js library has a ton of useful functionality in this regard.

    Here's an example of a manual parsing function that accepts these US formats:

    mm-dd-yyyy
    mm dd yyyy
    mm/dd/yyyy
    

    JS Code:

    function checkDate(str) {
        var matches = str.match(/(\d{1,2})[- \/](\d{1,2})[- \/](\d{4})/);
        if (!matches) return;
    
        // parse each piece and see if it makes a valid date object
        var month = parseInt(matches[1], 10);
        var day = parseInt(matches[2], 10);
        var year = parseInt(matches[3], 10);
        var date = new Date(year, month - 1, day);
        if (!date || !date.getTime()) return;
    
        // make sure we have no funny rollovers that the date object sometimes accepts
        // month > 12, day > what's allowed for the month
        if (date.getMonth() + 1 != month ||
            date.getFullYear() != year ||
            date.getDate() != day) {
                return;
            }
        return(date);
    }
    

    And a demo with some test cases: http://jsfiddle.net/jfriend00/xZmBY/

    If you want the Euro format, it's a trivial matter to switch the code to that. In either case, you have to decide which format you accept, code for it and then communicate to the user which format is required. If you think this is messy, then perhaps you will see why so many sites use a date calendar picker that doesn't have this complexity.

    0 讨论(0)
  • 2021-01-15 09:44

    new Date() doesn't throw an exception if month>12 for example, you can use Date.parse() and test the returned value with isNaN()

    0 讨论(0)
  • 2021-01-15 10:00

    Please correct or explain how my over-simplification is incorrect as I am not a JavaScript expert.

    But I just need to know if an object is a valid date. This will only come from user input (ie, text box).

    Here's why it's an oversimplification.

    First of all, it sounds like you really want to check the validity of a string representation of a Date object. This is not particularly useful by itself, because you are going to want to use the date for something in your script, send it to the server, etc.

    If you want to use the date in your script, there are caveats.

    new Date('2020-10-10') // Fri Oct 09 2020 20:00:00 GMT-0400 (EDT)
    

    If you want to pass it to the server, you'll need to do more than just check validity– you'll need to use a format that your server side code can interpret.

    If that's the case, you could consider normalizing the string into a format of your choice. You'd want to be able to create equivalent dates from the normalized strings in both your client and server side code. For simplicity, the format can be human-readable (not a timestamp), and you can replace the value of the text input with the normalized string.

    Checking the validity of the string can simply be a part of normalization... have the function return false or an empty string if the input was bad, don't change the text input's value, and instead show a message indicating that the value is invalid:

    // assume `birthday` is a text input.
    
    birthday.onblur = function() {
        
        var dateString = normalizeDate(birthday.value);
        
        if (dateString) {
            validator.style.display = 'none';
            birthday.value = dateString;
        } else {
            validator.style.display = 'block';
        }
            
    }; 
    

    Here's an example of what the normalizeDate function might look like. This example uses the format 'yyyy-mm-dd', you can change it to suit your needs.

    function normalizeDate(dateString) {
    
        // If it's not at least 6 characters long (8/8/88), give up.
        if (dateString.length && dateString.length < 6) {
            return '';
        }
    
        var date = new Date(dateString), 
            month, day;
    
        // If input format was in UTC time, adjust it to local.
        if (date.getHours() || date.getMinutes()) {
            date.setMinutes(date.getTimezoneOffset());
        }
        
        month = date.getMonth() + 1;
        day = date.getDate();
        
        // Return empty string for invalid dates
        if (!day) {
            return '';
        }
        
        // Return the normalized string.
        return date.getFullYear() + '-' +
            (month > 9 ? '' : '0') + month + '-' + 
            (day > 9 ? '' : '0') + day;
    }
    

    Here's the obligatory live demo.

    0 讨论(0)
提交回复
热议问题