javascript - 如何在 javascript 中检测 bool 值 true 和 false?

标签 javascript jquery html

<分区>

这是我的日期验证代码,当将 28/02/2017 填入输入类型文本并按下按钮时。

首先,如果第一个警报是 true,它会在代码中看到 true 警报,第二个警报也会警报 true。但我的第二个是警报 false

我对检测 bool 值的错误是什么

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>

最佳答案

原因是 regex.test() 将搜索字符串,如果匹配则返回 true。如果您随后再次调用 .test(),它将从中断的地方继续。

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

来自这里:MDN web docs – RegExp.prototype.test()

关于javascript - 如何在 javascript 中检测 bool 值 true 和 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50046711/

相关文章:

javascript - 无法弄清楚如何使用类名 cboxPhoto 获取特定 img 的 src(完整路径)

jquery - 使用 Jquery 选中/取消选中父/子复选框

Jquery 将文本添加到跨度

html - 为什么这个 CSS margin-top 样式不起作用?

javascript - 使用 raycaster 选择 gltf 的特定元素并添加事件监听器

javascript - 重用 HTML 代码块

javascript - React,如何更改下拉菜单选项? jQuery?

html - ios safari 中的 flex 元素离开屏幕

javascript - fullPage.js,内容 div 未正确放置

javascript - 使用 mongoose 使用 OR 条件删除 MongoDB 中的文档