Disable sequential text space using jquery

I want to disable consecutive multiple spaces in an asp.net textbox using jQuery.

The text field should not accept something like

Hello    World

 $(document).ready(function () {
            $('#txtFeedDesc').keydown(function (e) {
                if (e.ctrlKey || e.altKey) {
                    e.preventDefault();
                }
                else {
                    var key = e.keyCode;
                    var name = document.getElementById('<%=txtFeedDesc.ClientID %>').value;
                    if (!((key == 8) || (key == 32) || (key == 42) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105))) {
                        e.preventDefault();
                        return false;
                    }
                    else {
                        if (name.length < 50 || key == 8) {
                            return true;
                        }
                        else {
                            return false;
                        }
                    }
                }
            });
        });

This is a text box that accepts alphanumeric characters. I do not want two consecutive spaces

+3
source share
3 answers

using jquery and javascript

   var re = new RegExp("[ ]{2,}");
  if (("Hello   world").match(re)) 
  {
    alert("multiple space found in the string");
  } else 
  {
    alert("string is ok");
  }

Jsfiddle demo

+1
source

You can use it RegularExpresisonValidator, or it ValidationExpressioncan be like

"""^              # Start of string
    (?![ ])       # Assert no space at the start
    (?!.*[ ]{2})  # Assert no two spaces in the middle
    (?!.*[ ]$)    # Assert no space at the end
    [A-Z. ]{8,20} # Match 8-20 ASCII letters, dots or spaces
    $             # End of string"""
0
source
function trim (s)
{    
    s.value =  s.value.replace (/(^\s*)|(\s*$)/,""); 
    s.value =  s.value.replace (/[ ]{2,}/gi,"");     
    s.value = s.value.replace (/\n +/,"\n");           
    return;
}

The text field does not allow multiple spaces between two words

-1
source

All Articles