Sybrentjuh
Sybrentjuh

Reputation: 287

Why doesn't my function to check valid date work?

So I made a script that checks on keyup of input field, if the date is valid. If it matches the regular expression, it should add class date-valid so that the borders turn green (added in stylesheet).

My code:

document.getElementById("date-check").addEventListener("keyup", dateValid);

function dateValid() {
 var dateinput = document.getElementById("date-check");

    // regular expression to match required date format
    re = /^\d{1,2}\-\d{1,2}\-\d{4}$/;

    if(!dateinput.value.match(re)) {
      dateinput.classList.add('valid-date');
    }
}
input[type="date"].valid-date {
border: 1px solid green; 
}
<input type="date" id="date-check" class="form-control calender-black" name="dbfield52">

The problem is, now it checks if it doesn't match the regular expression and then add the border. But it should add the border if it matches the reg. When I change it to if(dateinput.value.match(re)) it doesn't work.

Upvotes: 0

Views: 55

Answers (1)

mplungjan
mplungjan

Reputation: 178010

Because the value is not what you see

const re = /^\d{4}\-\d{2}\-\d{2}$/; // 2020-07-10 is what I get in Chrome for value
document.getElementById("date-check").addEventListener("change", dateValid);

function dateValid() {
  console.log(this.value, re.test(this.value));
  this.classList.toggle('valid-date', re.test(this.value));
}
.valid-date {
  border: 3px solid green;
}
<input type="date" id="date-check" class="form-control calender-black" name="dbfield52">

Upvotes: 2

Related Questions