Do not allow a textbox to have a space between text RRS feed

  • Question

  • User1052662409 posted

    Hi All,

    I am looking for a solution, so that I can restrict user to have a space in a textbox's text.

    I got one as below

            function RestrictSpace() {
                if (event.keyCode == 32) {
                    event.returnValue = false;
                    return false;

    It is working fine. It doesn't allow user to type space using space-bar key. But If I copy a text like Alex John, it accept it, as it have the space between name.

    I also want to restrict it like if I paste Alex John it should itself convert like AlexJohn.

    Please Suggest

    Friday, March 30, 2018 5:26 PM


All replies

  • User-369506445 posted


    please try below code :

    <input type="text" id="txt"/>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script language="javascript" type="text/javascript">
        $('#txt').on("input", function () {
            $(this).val($(this).val().replace(/ /g, ""));
            //alert("you can't insert space on text-box");

    I hope that be helpful

    Saturday, March 31, 2018 2:40 PM
  • User-1838255255 posted

    Hi demoninside9,

    According to your description and needs, please check the following sample code:

        <meta charset="utf-8" />
        <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
            $(function () {
                $("#Text1").blur(function () {
                    var txt = $(this).val();
                    var newtxt = txt.replace(/\ /g, '');
        <input id="Text1" type="text" />

    Best Regards,

    Eric Du 

    Monday, April 2, 2018 5:58 AM
  • User516094431 posted

    As per you need, you can use one another option that "Disable Cut Copy Paste".

    Disable cut, copy and paste in textbox using jquery, javascript

    Not Allow Space on Key Press and Paste 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 2, 2018 6:22 AM