【发布时间】:2020-08-11 14:58:19
【问题描述】:
我从here 找到了这段代码。它将正则表达式验证功能添加到文本区域。它有效,但我不知道要使用正确的正则表达式来做我想做的事。
$(document).ready(function() {
var errorMessage = "Please match the specified format.";
$(this).find("textarea").on("input change propertychange", function() {
var pattern = $(this).attr("pattern");
if (typeof pattern !== typeof undefined && pattern !== false) {
var patternRegex = new RegExp("^" + pattern.replace(/^\^|\$$/g, '') + "$", "g");
var hasError = !$(this).val().match(patternRegex);
if (typeof this.setCustomValidity === "function") {
this.setCustomValidity(hasError ? errorMessage : "");
} else {
$(this).toggleClass("error", !!hasError);
$(this).toggleClass("ok", !hasError);
if (hasError) {
$(this).attr("title", errorMessage);
} else {
$(this).removeAttr("title");
}
}
}
});
$("#reset").click(function() {
$("#form1").reset();
if ($('[name ="textA5"]').hasClass("error")) {
$("#form1").toggleClass("error");
}
});
});
.error {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="form1" id="form1">
<textarea name="textA5" rows="8" cols="80" wrap="off" pattern="^([A-Za-z0-9-_]{1,}\|{2}(unlimited)(\r\n|\n|\r){0,1}){1,}$"></textarea>
<span class="errMSG">You have an error. Check format.</span>
<input class="buttons" type="reset" name="Reset" id="reset" value="Reset" />
<input class="buttons" type="submit" value="Save Configuration" />
</form>
我无法让我的正则表达式按预期工作。
pattern="^([A-Za-z0-9-_]{1,}\|{2}(unlimited)(\r\n|\n|\r){0,1}){1,}$"
为简单起见,请在此示例中明确使用 2||unlimited,即使正则表达式允许其他字符。
正则表达式应该只允许每行有一个 2||unlimited 实例,并且文本区域中不能有空行。
不幸的是,我当前的正则表达式也允许 2||unlimited2||unlimited。
我应该对正则表达式进行哪些更改?
【问题讨论】:
-
换行符是可选的,你可以添加断言字符串的结尾。
^(?:[\w-]+\|{2}unlimited(?:\r?\n|$))+$regex101.com/r/LBTFUe/1
标签: javascript jquery regex