如何在ng-pattern中使用正则表达式排除指定特殊字符?
Got it, let's adjust your ng-pattern to only block the specific special characters you listed (% ; : ' " < >) instead of all non-alphanumeric characters. Here's how to do it:
The Correct Regex Pattern
Instead of whitelisting only alphanumeric characters, we'll use a negated character class to blacklist exactly the characters you want to exclude. The regex will look like this:
/^[^%;:\x27\x22<>]*$/
Breakdown of the Pattern
Let's break down what each part does:
^: Anchors the match to the start of the string[^...]: Negated character class—matches any character not inside the brackets%;:\x27\x22<>: The list of characters to exclude:%,;,:are straightforward to include\x27is the hex escape for the single quote (') to avoid quote conflicts in the HTML attribute\x22is the hex escape for the double quote (") for the same reason<,>are added directly
*: Allows zero or more of the allowed characters (anything not in the blacklist)$: Anchors the match to the end of the string
Updated Input Element
Here's how your input tag should look with the corrected pattern:
<input type="text" class="txt_box" ng-disabled="filechoosen" name="file_name" ng-pattern="/^[^%;:\x27\x22<>]*$/" ng-model="filenameedit" id="filenameedit"> <div style="color:Red" ng-show="file_name.$error.pattern ">禁止使用以下特殊字符:%、;、:、'、"、<、></div>
Quick Note on Your Original Updated Code
I noticed your initial updated pattern included extra characters like {}[]/—if you didn't intend to exclude those, just remove them from the negated character class. If you do want to block those too, keep them in the brackets like you had before.
内容的提问来源于stack exchange,提问作者Vishnu

