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>

1
  • 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 Commented Apr 26, 2018 at 15:29

1 Answer 1

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()

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

7 Comments

work good sir..
Just a question, why it is working if you remove g modifier? thanks!
@Albeis If you remove the global flag it searches from the beginning every time.
Thanks! so removing global flag should be another solution right? regards
@Albeis ‘g’ stands for ‘global’ – the g modifier sets the global flag. And that affects the “If the regex has the global flag set” behavior described in the documentation.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.