简体   繁体   中英

advanced regex pattern for html5 input

I can't seem to put together a working pattern to disallow all html tags except for the strong and em tag.

I don't want to parse the html but just want to give the user a warning that the input will not be accepted. I am aware that this is not supported in all browsers but I would love a pure html solution, as I already have a working JS solution, but I wan't to layer the user experience.

<input name="user_input" pattern="^(?!<[^>]*>).*$" />

So allowed tags: strong, em the use of all other tags should make the result false

Any one able to crack this one?

KR

edit:

<input type="text" pattern="((?!<(?!\/?(strong|em))[^>]*>).)*">

is what seems to do the trick. Thank you for your help!

You can use a Negative Lookahead (?!) for this purpose.

An example regex string which matches the entire pair:

<(?!\\/?strong|\\/?em)[^>]*>.*(?:<\\/.*?>)?

A shorter regex, which matches the first tag only

<(?!\\/?(strong|em))[^>]*>


This match will pass if a HTML tag with something EXCEPT strong or em exists.

So, if match = $true, you can deny the input and give the user a warning.


Regex101 demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM