Search code examples
javascriptc#asp.netxmlumbraco

check Multiple Word in Input Field textbox using javascript


I am having textbox Input field and in that i have to check Multiple words. I am able to check single Word but not able to check multiple words. A list of word is stored in xml and from that i have to check. Need Help. Here MyName is Input Field Id and lblMyName is Label Id.

           if ($("#MyName").val() != '') {
                $.ajax({
                    type: "GET",
                    url: "Xml/Badwords.xml",
                    dataType: "xml",
                    success: function (xml) {

                        $(xml).find('Badwords').each(function () {

                             var flag = true;

                            $(this).children().each(function () {

                                var tagName = this.tagName;
                                var val = $(this).text();

         if (val.toLowerCase() == $("#MyName").val().toLowerCase())                       {
                                    $("#lblMyName").css("display", "block");

                                    $("#lblMyName").text("Please refrain from using profanity.");
                                    $(".postermyname").text('My Name);
                                     flag = false;
                                    return false;                                                                       

                                }

Solution

  • You'll have to split the input value on word boundaries and then compare that against the "bad" words.

    Note that profanity filters is in generally a really bad idea, and will usually cause more issues than they solve

    if ( $("#MyName").val().trim() != '' ) {
        $.ajax({
            type: "GET",
            url: "Xml/Badwords.xml",
            dataType: "xml",
            success: function(xml) {
    
                var input = $("#MyName").val().toLowerCase().split(/\b/),
                    flag  = true;
    
                $(xml).find('Badwords').each(function() {
                    $(this).children().each(function() {
                        var val = $(this).text().toLowerCase;
    
                        if (input.indexOf(val) !== -1) {
                            $("#lblMyName").css("display", "block")
                                           .text("Please refrain from using profanity.");
                            flag = false;
                        }
                    });
                });
            });
        });
    }