3

This is my code for date validate, when fill 28/02/2017 into input type text and press button.

First it's will alert true when see in code if first alert is true secone alert will alert true too. But my second is alert false.

What is my miskate for detect boolean

if(regex.test(txt) === true)
{
    alert("true");
    p.innerHTML = "<h1 style='color:green'>Correct</h1>";
}
else
{
    alert("false");
    p.innerHTML = "<h1 style='color:red'>Wrong</h1>";;
}

.

<input type="text" id="date" name="date" value="dd/mm/yyyy" />
<button onclick="isDate();">Check</button>

<p id="response"></p>
<script>
function isDate() {
    
    var regex = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g;
    
    var txt = document.getElementById("date").value;
    var p = document.getElementById("response");
    
 alert(regex.test(txt));
 
 if(regex.test(txt) === true)
 {
  alert("true");
  p.innerHTML = "<h1 style='color:green'>Correct</h1>";
 }
 else
 {
  alert("false");
  p.innerHTML = "<h1 style='color:red'>Wrong</h1>";;
 }  
} 
</script>
reswe teryuio
  • 117
  • 1
  • 1
  • 8
  • For some reason, adding console.log below the alert repeating the test, then removing the `===` and `true` it returns true then logs false... VERY strange!! spoookky – L_Church Apr 26 '18 at 15:29

1 Answers1

7

The reason is that regex.test() will search the string and return true if there is a match. If you then subsequently call .test() again it will continue from where it left off.

Using test() on a regex with the global flag

If the regex has the global flag set, test() will advance the lastIndex of the regex. A subsequent use of test() will start the search at the substring of str specified by lastIndex (exec() will also advance the lastIndex property).

From here: MDN web docs – RegExp.prototype.test()

Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67