Reputation: 497
I found this code from here. It adds regex validation functionality to a textarea. It works but I cant figure out the correct regex to use, to do what I want.
$(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>
I can't get my regex to work as intended.
pattern="^([A-Za-z0-9-_]{1,}\|{2}(unlimited)(\r\n|\n|\r){0,1}){1,}$"
To keep it simple, use 2||unlimited, explicitly, in this example even though the regex will allow other characters.
The regex should allow only one instance of 2||unlimited per line and no empty lines in the textarea.
Unfortunately, my current regex also allows 2||unlimited2||unlimited.
What changes should I make to the regex?
Upvotes: 1
Views: 649
Reputation: 163277
In the pattern that you tried, you are repeating the outer group 1 or more times, and inside the group you are matching 1 or more times [A-Za-z0-9-_]+
, then \|{2}(unlimited)
.
Due to the repetition of the outer group and the optional newline, the pattern can match 1 or more times the 2||unlimited
pattern
You could start the match with [A-Za-z0-9-_]+
or [\w-]+
and then match the double pipe and unlimited at the end of the string.
^(?:[\w-]+\|{2}unlimited(?:\r?\n|$))+$
Upvotes: 1