我是编码新手,因为我相信您能够从我的问题中看出,因为我觉得这应该很容易完成,但我为此奋斗的时间比我愿意承认的要长,现在必须要求指导。
在下面的代码中,每次输入时我都会收到“不是邮政编码”的警报 - 无论它是否是有效的邮政编码。
$("body").on("click", "#searchBtn", function (event) {
event.preventDefault();
// The below is a regular expression (regex) to ensure user enters either a 5 digit or 9 digit US zip code format
var zip = ("^[0-9]{5}(?:-[0-9]{4})?$;");
var input = $("#userInput").val().trim();
if (input!=zip) {
alert("Not a Zip Code"); //the end goal is to have the placeholder color turn red
} else {
alert("Thank you - your entry is valid"); //the end goal is to have the placeholder say "You are searching in zip code " (+ zip)"
};
});
为了解决这个问题 - 当我替换:alert("Not a Zip Code"); 使用(此时我已经尝试了多种格式,但一个例子是:
$("#userInput").addClass('red');
对于上述内容,我在 CSS 中添加了以下内容:
.red::placeholder {
color: red;
}
我也在这个板上搜索过类似的问题,但它们要么比我目前的理解更高级,要么使用我还不熟悉的程序。 预先感谢您的帮助!
最佳答案
- 使用JS的RegExp.prototype.test()
- 使用 jQuery 的
.toggleClass()
method - 对美国邮政编码使用这个更简单的正则表达式:
^\d{5}(-\d{4})?$
$("body").on("click", "#searchBtn", function(event) {
event.preventDefault();
var $input = $("#userInput");
var input = $input.val().trim();
// Ensure user enters either a 5 digit or 9 digit US zip code format
var isValid = /^\d{5}(-\d{4})?$/.test(input);
$input.toggleClass('is-invalid', !isValid);
alert(isValid ? "Thank you - your entry is valid" : "Not a Zip Code");
});
.is-invalid::placeholder { /* Don't use color-specific classes! */
color: red;
}
<input id="userInput" type="text" placeholder="Enter US ZIP code">
<button id="searchBtn">SEARCH</button>
<script src="//code.jquery.com/jquery.min.js"></script>
关于jquery - 尝试验证用户输入时出现基本 jQuery 语法问题 - 请告知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60742869/