使用JavaScript正则表达式验证输入
我使用这个JS函数来验证用户输入,并确保它是2000-2021年之间的一年,它工作得很好,问题是当我写无效输入时,它会将大纲更改为红色,但是当我写有效输入时,它保持红色。即使我从一开始就写了有效的输入,它也会变成红色使用JavaScript正则表达式验证输入,javascript,regex,validation,dom,Javascript,Regex,Validation,Dom,我使用这个JS函数来验证用户输入,并确保它是2000-2021年之间的一年,它工作得很好,问题是当我写无效输入时,它会将大纲更改为红色,但是当我写有效输入时,它保持红色。即使我从一开始就写了有效的输入,它也会变成红色 var batchRegex=/^[2][0][0-2][0-1]$/; function checkBatch(batch){ if (batch = ""){ document.getElementById('batch').style.outline
var batchRegex=/^[2][0][0-2][0-1]$/;
function checkBatch(batch){
if (batch = ""){
document.getElementById('batch').style.outlineColor = "red";
}
else if(!batchRegex.test(batch)){
document.getElementById('batch').style.outlineColor = "red";
}
else if(batchRegex.test(batch)){
document.getElementById('batch').style.outlineColor = "none";
}
}
<form method="post">
<input type="text" maxlength="4" id="batch" name="batch" onkeyup="checkBatch(this.value)" required>
<input type="submit" name="submit">
</form>
var batchRegex=/^[2][0][0-2][0-1]$/;
函数checkBatch(批处理){
如果(批次=”){
document.getElementById('batch').style.outlineColor=“红色”;
}
如果(!batchRegex.test(batch)){
document.getElementById('batch').style.outlineColor=“红色”;
}
else if(批处理正则表达式测试(批次)){
document.getElementById('batch').style.outlineColor=“无”;
}
}
您的代码中存在多个问题:
if(batch=”“){
应该是if(batch==”){
/^[2][0][0-2][0-1]$/
仅匹配以下值:
2000
,2001
,2010
,2011
,2020
,2021
2000
和2021
之间的所有值
为什么不试试这样简单的方法:
函数检查批处理(批处理){
如果(batch.value>=2000&&batch.value不使用JS更改输入的样式,请使用HTML5和CSS中提供的内置输入验证。使用CSS自动处理和更新样式
如果使用数字输入,则可以放置最小值和最大值
<input type="number" min=2000 max=2021 name="numyr" required >
如果您坚持在输入值上使用正则表达式,那么可以使用模式
属性
<input type="text" pattern="^[2][0][0-2][0-1]$" >
输入{
最小宽度:100px;
显示:块;
保证金:5px;
}
输入:无效{
外形:2倍纯红;
}
regex在哪里?试试模糊事件对不起,我忘了包括它,这里是var batchRegex=/^[2][0][0-2][0-1]$/;
@MaheerAli@herosuper它一点也不改变颜色all@herosuper我不确定,但在没有之前,我尝试了绿色,但没有工作
<input type="text" pattern="^[2][0][0-2][0-1]$" >