简体   繁体   中英

Regular Expression to avoid HTML tags and empty values

I have applied a textbox click validation and wanted to avoid any html tags in text box also the simple < (open tag) and >(close tag). The below code is working for but i want to add additional validations also for empty strings and other tags in html. Can some one please help modify the regex for the requirement.

function htmlValidation() 
 {
   var re = /(<([^>]+)>)/gi;

   if (document.getElementById(’<%=TextBox2.ClientID%>’).value.match(re)){ document.getElementById(’<%=TextBox2.ClientID%>’).value = “”;
          return false;
        }
   return true;
 }

Corrected Code above

In my opinion, I believe you'll have a good hard work if you want to validate such things.

Instead of preventing HTML content in a text box, other solution could be just html entity encode Text property, so <p>a</p> would be converted to &gt;p&lt;a&gt;p&lt; .

Result of that is you're going to render the HTML "as text" instead of getting it interpreted by Web browser.

Check this MSDN article:

$("#<%= btnAdd.ClientID %>").click(function () {
            var txt = $("#<%= txtBox1.ClientID %>");
            var svc = $(txt).val();  //Its Let you know the textbox's value 
            var re = /(<([^>]+)>)/gi;
            if(txt.val()!=""){
            if (!txt.val().match(re)) {
               //my Operations 
               //goes here
                });
                return false;
            }
            else {
                alert("Invalid Content");
            }
            }
            else {
            alert("Blank value selected");
            }

I have used Jquery function to check for regular expresion. This question is a linked question with Using Jquery to add items in Listbox from Textbox

Now i can mark this as my final answer.

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