0

I have this regex code below to validate a valid date.

function isValidDate(div) {
var reg = /^((0?\d)|(1[012]))\/([012]?\d|30|31)\/\d{1,4}$/;
var regs = /^\/\d{1,4}$/;
var dateField = $(div).val();
if (dateField == "") {
    //alert('Invalid inclusive dates.');
    return false;
} else {
    if (reg.test(dateField) == false && regs.test(dateField) == false) {
      // alert('Invalid inclusive dates.');
        return false;
    } else {
        return true;
    }
  }
}

I am testing this code as you can see I have 2 condition in if (reg.test(dateField) == false && regs.test(dateField) == false) {. In this line I am testing if the date is full date(1/1/2017) or (2017) only. If I input that two different dates it return false because of the condition. How to achieve this?.

KiRa
  • 924
  • 3
  • 17
  • 42
  • I'm not sure of what exactly are you asking. Please clarify – Rajesh Jan 04 '17 at 06:24
  • If you just want a regular expression to test patterns for "1/1/2017" or "2017", they can be very much simpler than what you have, e.g `/$\d{1,2}\/\d{1,2}\/\d{4}$/` and `/^\d{4}$/`. If you want to also validate the values, that's another story (and should not use a regular expression). – RobG Jan 04 '17 at 06:25
  • @Rajesh If user input 1/1/2017 or 2017 it will return as true. otherwise it return false. – KiRa Jan 04 '17 at 06:28
  • *regs* seems to be testing for "/2017". – RobG Jan 04 '17 at 06:29
  • @RobG yes. but I am having trouble in `else` condition – KiRa Jan 04 '17 at 06:29
  • var dateField = $(div).val(); what does this line mean..? can you pls update if you mean it as a div element or an input field – SAMUEL Jan 04 '17 at 06:32
  • `$(div).val();` refer to my id of a datepicker – KiRa Jan 04 '17 at 06:34
  • Possibly a duplicate of [*How to validate a date?*](http://stackoverflow.com/questions/5812220/how-to-validate-a-date/5812341#5812341). Your issue is with *regs*, there is an erroneous leading slash, it should be `var regs = /^\d{1,4}$/`. – RobG Jan 04 '17 at 06:34
  • @RobG if i input year I want to read it as true. For example I input 2 dates `1/1/2017` and year `2017` it should be read as true :( – KiRa Jan 04 '17 at 06:43
  • @RobG its okay now i added an `else if` – KiRa Jan 04 '17 at 07:27

1 Answers1

1

Make day and month optional:

var reg = /^(?:(0?\d|1[012])\/(0?[1-9]|[12]\d|30|31)\/)?\d{1,4}$/;
//          ^^^                                       ^^  
Toto
  • 89,455
  • 62
  • 89
  • 125