0

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.

2
  • 2
    With type="date" and a browser that supports it, the user cannot choose the format of the date, the browser does for him. Commented Jul 9, 2020 at 7:53
  • Why String.prototype.match()? Use RegExp.prototype.test() when you only need true/false Commented Jul 9, 2020 at 7:53

1 Answer 1

2

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">

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I didn't think of this. Now it works perfectly, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.