0

I'm working on ASP.NET with C#.

I have a TextBox and I want to validate if the user is writing the correct length for the TextBox.

If the user is not entering the correct length I want a message to display on a label. But I want this check to happen on the fly, as the user is writing.

How can I do this?

Thanks.

Martin-Brennan
  • 917
  • 7
  • 19
pyram
  • 925
  • 9
  • 24
  • 43

2 Answers2

2

suppose these are your asp.net elements

<asp:label id="message" runat="server"/><br/>
<asp:textbox runat="server" id="txtTest"/>

your js should be something like:

$(function(){
    $("input[id$='txtTest']").bind('keypress', function(){   
        if($("input[id$='txtTest']").val().length < 10)
            $("[id$='message']").text('incorrect length');
       else
        $("[id$='message']").text('');
    });
});

note that id$='message and input[id$='txtTest'] in jQuery means id ends with

When you mark an element to be run at server, asp.net append some other names at the start of the actual client id based on the name of you page.

and here is working demo

Community
  • 1
  • 1
Amir
  • 9,577
  • 11
  • 41
  • 58
  • Thanks. Its working.......But if I write the desired length on the textbox, and then erase characters with backspace button on keyboard so it would go under the desired length, the message does not show up again...How can I modify it so it can detect when the backspace button is deleting characters? – pyram Sep 21 '12 at 16:16
  • On the working demo you posted the backspace button works, but when I test it on my machine it doesn't. – pyram Sep 21 '12 at 16:30
  • @pyram, could you post your code, and I'll see what's the discrepancy then. – Amir Sep 22 '12 at 03:00
1

Use jQuery for it. Have a div next to your textbox, hook up an onchange() event for your textbox, and just have jQuery populate the div with your message if the length of the textbox's val() is not long enough.

<input type="text" id="myTextBox" onchange="changeMessage" />
<div id="message"></div>

<script>
function changeMessage(){

  var textboxLength = $('#myTextBox').val().length;
  if(textboxLength < ...){
    $('#message').html('Your Message');
  }
}
</script>
Corey Adler
  • 15,897
  • 18
  • 66
  • 80