Tuesday 2 January 2018

Checking For Bad/Abuse Words On Form Posting Using An XML File In C#

Here is a simple code snippet to restrict users from entering bad or abuse words on your website forms.

This is very useful in feedback forms, comments sections, etc..

Step 1: Create a aspx page “Bad-words-check.aspx” as below.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Bad-words-check.aspx.cs"  
  
Inherits="ResponsiveForms_ASP_NET_Bad_words_Bad_words_check" %>  
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    <html xmlns="http://www.w3.org/1999/xhtml">  
  
    <head id="Head1" runat="server">  
        <title></title>  
        <style>  
            body {  
                font-family: 'Arial';  
            }  
        </style>  
    </head>    
    <body>  
        <form id="form2" runat="server">  
            <div> <textarea runat="server" id="txtmsg" class="txtarea Txtbox" rows="6" cols="50" style="resize: none;  
  
width: 300px; height: 120px;"></textarea> <br /><br />  
                <asp:Button ID="btnpost" ClientIDMode="Static" runat="server" Text="SUBMIT" Width="100px" OnClick="btnpost_Click" /> <br /><br />  
                <asp:Label ID="lblmsg" runat="server" style="color:Red;font-weight:bold;"></asp:Label>  
            </div>  
        </form>  
    </body>  
</html>   


Step 2: Make cs file as below,

using System;  
using System.Collections.Generic;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Xml;  
public partial class ResponsiveForms_ASP_NET_Bad_words_Bad_words_check: System.Web.UI.Page {  
    protected void Page_Load(object sender, EventArgs e) {}  
    protected void btnpost_Click(object sender, EventArgs e) {  
        try {  
            XmlDocument xmlDoc = new XmlDocument(); // Create an XML document object  
            xmlDoc.Load(Server.MapPath("../WordList.xml")); // Load the XML document from the specified file  
            // Get elements  
            XmlNodeList badwords = xmlDoc.GetElementsByTagName("word");  
            for (int i = 0; i < badwords.Count; i++) {  
                if (txtmsg.Value.ToUpperInvariant().Contains(badwords[i].InnerText.ToUpperInvariant())) {  
                    lblmsg.Text = "Your text contains bad/abuse words!";  
                    break;  
                } else lblmsg.Text = "Your text is clean!";  
            }  
        } catch (Exception ex) {}  
    }  
}  

Step 3: Add xml file “WordList.xml” to your project,

Now you can run the page and see the result. If you have any further words to be restricted then you can add it manually to the xml file.

For the source code of the pages and xml file, pelase visit the blog I have written in C-Sharpcorner website - Click here.

No comments:

Post a Comment