info perto
info perto

Reputation: 89

ASP.NET error message if textbox is empty or too short

I have tried following code however there was no change and it doesnt show the error message.

  if (TextBox1.Text.Length<500 || TextBox1.Text.Length == 0)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(),"Scripts","<script>alert('Input is empty or too short.');</script>");


        }

Upvotes: 0

Views: 1879

Answers (1)

Denys Wessels
Denys Wessels

Reputation: 17049

The example below will execute a javascript function which will check for validity of TextBox1 and display an error message if the length is less than 500.If the length is 500 or more the validation passed and the server side Button1_Click will execute.

<head runat="server">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
    <script type="text/javascript">
        function CheckValidInput() {
            var textLength = $("#TextBox1").val().length;

            if (textLength < 500) {
                alert("Input is empty or too short.");
                return false;
            }
            return true;
        };
    </script>
</head>
<body>
    <form runat="server">
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return CheckValidInput()" OnClick="Button1_Click" />
    </form>
</body>

Upvotes: 1

Related Questions