Search This Blog

Wednesday 9 October 2019

Allow only one space between words in javascript

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script>
        //Way 1
        function Validate1() {
            var a = document.getElementById("TextBox1").value;
            var b = a.split(' ');
            var c = 0;
            for (var i = 0; i < b.length; i++) {
                if (b[i] == '') {
                    c++;
                    if (c == 2) {
                        document.getElementById("TextBox1").value = a.substring(0, a.length - 1);
                        return false;
                    }
                }
            }
        }
        //Way 2
        function Validate2() {
            var a = document.getElementById("TextBox2").value;
            var b = a.split(' ');
            var c = 0;
            for (var i = 0; i < b.length; i++) {
                if (b[i] == '') {
                    c++;
                    if (c == 2) {
                        alert('Only one space allowed in/between the word.');
                        document.getElementById("TextBox2").value = a.substring(0, a.length - 1);
                        return false;
                    }
                }
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            Way 1 (Without Message) :-<asp:TextBox ID="TextBox1" runat="server" onkeyup="Validate1();" ClientIDMode="Static"></asp:TextBox>
            <br />
            <br />
            Way 2 (Alert With Message) :-<asp:TextBox ID="TextBox2" runat="server" onkeyup="Validate2();" ClientIDMode="Static"></asp:TextBox>
        </div>
    </form>
</body>
</html>