Skip to content
Advertisement

Remove HTML tags from input before sending

I have some chat script and I’m trying to filter the input field before clicking send or submit. This is my input filed:

<input required type="text" name="content"  maxlength="300" id="content" placeholder="Write Your Message.."  autocomplete="off">

submit

 <button type="submit" class="sound-btn" id="submit_button">
        <i class="fa fa-paper-plane"></i>
    </button>

when im trying to send some tags like

<img src="avatar/user1_13128662_tumb.jpg">
<div id="test">
demo text
</div>

unfortunately is working

what i need to do.. remove all attr tags from input or prevent to write html tags inside input because all of this data saved in database and very dangerous and allow xss injected too something like this

<b>
<div>
</div>
<img
<a
<li
<ul
and all the HTML tags just keep links and numbers and normal text

I think all HTML tags what I need to keep http and https and mailto: and the normal text and numbers just filter unwanted characters before to send by javascript or jquery ..thanks

Advertisement

Answer

You could apply a simple regex to the onchange Event of your input :

document.getElementById('content').addEventListener('change', (e)=> {
    let tValue = e.target.value.replace(/<[^>]+>/gim, '');
    e.target.value = tValue;
});
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement