javascript - 使用 JavaScript RegEx 验证输入
问题描述
我有这个 JS 函数来验证用户输入并确保它是 2000-2021 之间的一年,它工作得很好,问题是当我写无效输入时它会将轮廓更改为红色,但是当我写一个有效输入时它仍然存在红色的。即使我从一开始就写了有效的输入,它也会变红。
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>
解决方案
您的代码中有多个问题:
if (batch = ""){
应该if (batch == ""){
正则表达式
/^[2][0][0-2][0-1]$/
仅匹配值:2000
,2001
,2010
,2011
,2020
,2021
但您想匹配 和 之间的所有2000
值2021
。
为什么不尝试这样简单的事情:
function checkBatch(batch){
if (batch.value >= 2000 && batch.value <= 2021){
batch.style.outlineColor = "green";
} else {
batch.style.outlineColor = "red";
}
}
<form method="post">
<input type="text" maxlength="4" id="batch" name="batch" onkeyup="checkBatch(this)" required>
<input type="submit" name="submit">
</form>
而不是通过javascript更改内联样式,只需添加一个类,然后您可以使用CSS更改样式,例如..
function checkBatch(batch){
if (batch.value >= 2000 && batch.value <= 2021){
batch.classList.remove('alert')
batch.classList.add('success')
} else {
batch.classList.remove('success')
batch.classList.add('alert')
}
}
input.alert {
outline-color: red;
}
input.success {
outline-color: green;
}
<form method="post">
<input type="text" maxlength="4" id="batch" name="batch" onkeyup="checkBatch(this)" required>
<input type="submit" name="submit">
</form>
推荐阅读
- pandas - RFECV gridscore 中的数字是否等同于所选特征?
- flutter - 如何在 Flutter_linkify 上编辑 Hiperlink
- php - SQLSTATE[HY000]:一般错误:1364 字段“country_id”没有默认值
- function - 如何在 Go 中泛化函数包装?
- visual-studio-code - VSCode 扩展在 activityBar 中添加一个输入
- node.js - 使用 Jest 进行 Strapi 单元测试,失败
- javascript - 如何在 crome 浏览器的控制台上运行纯 Java 脚本文件
- java - 我无法在 android studio 上运行我的项目。每当我尝试下载模拟器时,它都会显示以下错误
- python-3.x - 您在 64 位操作系统(mac)上运行 32 位 Python,无法加载 XGBoost 库。可能的原因,Mac
- docker - 有没有办法在 gcp 中自动构建 kubeflow 管道