JavaScript - HTML detection

I have an HTML textarea element. I want to prevent the user from entering HTML tags in this area. How to determine if a user has entered any HTML code into a text box with JavaScript?

thank

0
source share
5 answers

firstly, keep in mind that you will need to repeat the server-side check, since anyone can fake the http message, and if they have javascript disabled, then of course you cannot control :)

what would i do

<textarea onkeypress="disableHtml(this);" name="text"></textarea>

and for javascript

function disableHtml(element) {
  element.value = element.value.replace(/[<>]/g, '');
}

another way to do this is to replace <and> with & lt; and? on the server side, which is better because it is safe and people can still frown> :)

[edit: regexp , , , , ]

-3

keypress false, < >. HTML "" "", . HTML ... , jQuery :

var sanitized = $('<div>').html(textareavalue).text();

, , , HTML . , , . , PHP htmlspecialchars() JSP/JSTL fn:escapeXml(). , Javascript // .

+5

:

  • XML!= HTML, , html , XML .
  • html , (escape html ).
  • , , ( ).

, html- '::

/**
* This function delete html tags from a text, even if the html tag is 
* not well formed.
* This function update the pointer position to maintain it after the replacement.
* @param {string} text The text to modify
* @param {int} initPos The current position of the pointer in the text 
* @return {int} The new pointer position
*/
function removeHtmlTags( text, initPos )
{
    // Define the regex to delete html tags
    if (undefined===removeHtmlTags.htmlTagRegexp)
    {
        removeHtmlTags.htmlTagRegexp = new RegExp('</?(?:article|aside|bdi|command|'+
            'details|dialog|summary|figure|figcaption|footer|header|hgroup|mark|'+
            'meter|nav|progress|ruby|rt|rp|section|time|wbr|audio|'+
            'video|source|embed|track|canvas|datalist|keygen|output|'+
            '!--|!DOCTYPE|a|abbr|address|area|b|base|bdo|blockquote|body|'+
            'br|button|canvas|caption|cite|code|col|colgroup|dd|del|dfn|div|'+
            'dl|dt|em|embed|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|'+
            'h5|h6|head|hr|html|i|iframe|img|input|ins|kdb|keygen|label|legend|'+
            'li|link|map|menu|meta|noscript|object|ol|optgroup|option|p|param|'+
            'pre|q|s|samp|script|select|small|source|span|strong|style|sub|'+
            'sup|table|tbody|td|textarea|tfoot|th|thead|title|tr|u|ul|var|'+
            'acronym|applet|basefont|big|center|dir|font|frame|'+
            'frameset|noframes|strike|tt)(?:(?: [^<>]*)>|>?)', 'i');
    }

    // Delete html tags
    var thereIsMore=true;
    removeHtmlTags.htmlTagRegexp.lastIndex=0;
    // While I am not sure that all html tags are removed.
    while (thereIsMore)
    {
        var str = text.match(removeHtmlTags.htmlTagRegexp);
        if ( str!=null) // There is a match
        {
            text = text.replace(str[0], '');
            // Update the position
            if (str.index < initPos) 
                initPos= Math.max(initPos-str[0].length,str.index);
        }
        else thereIsMore = false;
    }

    // If getCaretPosition fail, the initPos may be negative
    if (initPos<0) initPos=0;

    return {text: text, pos: initPos};
}

: , :

'<div>' -> ''
'<div selected' -> ' selected'
'<div selected>' -> ''
'<div    >' -> ''

-, , / carret, textarea reset. , , - .

/**
 * This function get/set the position of the carret in a node.
 * If the value is set, this function try to set the new position value.
 * Anyway, it return the (new) position.
 * @param {Element} node The textarea element
 * @param {int} value The new carret position
 * @return {int} The (new) carret position 
 */
function caretPosition(node, value) 
{
    // Set default Caret pos, will be returned if this function fail.
    var caretPos = 0;

    // Ensure that value is valid
    value = parseInt(value);

    // Set the new caret position if necesary
    if (!isNaN(value)) // We want to set the position
    {
        if (node.selectionStart)
        {
            node.selectionStart=value;
            node.selectionEnd= value;
        }
        else if(node.setSelectionRang)
        {
            node.focus();
            node.setSelectionRange(value, value);
        }
        else if (node.createTextRange)
        {
            var range = node.createTextRange();
            range.collapse(true);
            range.moveEnd('character', value);
            range.moveStart('character', value);
            range.select();
        }
    }

    // Get the position to return it.
    if (node.selectionStart) return node.selectionStart;
    else if (document.selection)
    {
        node.focus();
        var sel = document.selection.createRange();
        sel.moveStart('character', -node.value.length);
        caretPos = sel.text.length;
    }

    return caretPos;
}

-, html- carret.

/**
 * This event function remove html tags from the textarea with id=text 
 */
function updateText()
{
    // Get the textarea
    var t = document.getElementById('text');

    // Get the caret position
    var pos = caretPosition(t);

    // Remove html from the text
    var result = removeHtmlTags(t.value, pos);
    t.value = result.text;

    // Set the new caret position
    caretPosition(t, result.pos);
}

, :

  • Past

"oninput" , (ofc) IE .

HTML:

<html>
    <head>
        <script type="text/javascript">
           <!-- Copy all the js code here. -->
        </script>
    </head>
    <body>
        <textarea cols="50" rows="10" oninput="updateText();" 
            ondrop="setTimeout('updateText();',0);" 
            onpaste="setTimeout('updateText();',0);" 
            onkeyup="updateText();" id='text'></textarea>
    </body>
</html>

, :-) Escain

+3

,

if ( textArea.value.match(/<\/*[a-z][^>]+?>/gi) ) {
  // do something about it
}

"textArea" - textarea.

+2

HTML-? <b> ? I <3 how 5 is > 4?

, . .

0

All Articles