0

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!

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Nice! It works like you say it does, almost there now, but I can't control the true/false comparison so everything needs to happen within the pattern. It should give false as soon as a non em or strong tag is found. This should give true: My name is <strong>name</strong>. As for example where My name is <strong>name</strong> <span>test</span>. Should return false
The problem with matching in that fashion, is that it will match true in this as an example: <strong>words</strong><span>test</span> resulting in bad tags being accepted ... I'm assuming that your input will be more than one tag, is that true?
The matching or order is not important, all input is valid except for html tags other then the strong and em tag. I have been experimenting with your answer to invert the result but I can't get it to work.
After a good night of rest and your help I have been able to put togheter this: <input type="text" pattern="((?!&lt;(?!\/?(strong|em))[^&gt;]*&gt;).)*"> this seems to do what I want, all text is accepted unless an html tag aside 'em' or 'strong' has been used. Thank you very much Vasili!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.