javascript - How to invalid 00000000 date in JS - Stack Overflow

admin2025-04-09  0

I am using jQuery Validation Plugin. I used this post to validate my dates using this plugin. It is working but there is a problem. It is accepting 00/00/0000 date as well. How can I invalid this date as well by modifying following function.

$.validator.addMethod(
    "australianDate",
    function(value, element) {
        return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
    },
    "Please enter a date in the format dd/mm/yyyy"
);

I am using jQuery Validation Plugin. I used this post to validate my dates using this plugin. It is working but there is a problem. It is accepting 00/00/0000 date as well. How can I invalid this date as well by modifying following function.

$.validator.addMethod(
    "australianDate",
    function(value, element) {
        return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
    },
    "Please enter a date in the format dd/mm/yyyy"
);
Share Improve this question edited May 23, 2017 at 12:19 CommunityBot 11 silver badge asked May 11, 2011 at 6:54 AwanAwan 18.6k38 gold badges94 silver badges133 bronze badges 3
  • 3 First you need to decide what the valid dates should be. For example, is 11/11/1111 valid? How about 01/01/0001. How about 31/04/2010? It's quite hard to validate dates using only regular expressions. The regexp above captures most of the problems and allows a relatively sane date into the system. If you need more robust validation, you should write something that actually tries to parse the date taking into account the semantics of date, month and year and decide whether it's valid or not. Regexps can only go so far. – Noufal Ibrahim Commented May 11, 2011 at 7:01
  • @Noufal Ibrahim: Yes you are right but for now I just want to invalid a date with all zeros (00/00/0000). Thanks for your concern.. – Awan Commented May 11, 2011 at 7:04
  • @Noufal Ibrahim is right, different decision is causing different solution – bungdito Commented May 11, 2011 at 7:05
Add a ment  | 

3 Answers 3

Reset to default 3

This will ensure the data is in correct format and is also a valid date.

$.validator.addMethod(
    "australianDate",
    function(value, element) {
        var tokens =  value.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})/);

        if (tokens == null) {
            return false;
        }

        var date = new Date(tokens[3], --tokens[2], tokens[1]);

        return ! isNaN(date.getTime());

    },
    "Please enter a valid date in the format dd/mm/yyyy"
);

you can try:

function(value, element){
    return /^\d{1,2}\/\d{1,2}\/\d{4}$/.test(value) &&
        !isNaN(+new Date(value.split('/').reverse().join('/')));
}

maybe you can try this, perhaps it can works :)

function(value, element) {
        if (!value.match(/^00\/00\/0000$/)) return value;        
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744128078a232553.html

最新回复(0)