pyram
pyram

Reputation: 935

asp.net, validate as user is writing on textbox

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.

Upvotes: 0

Views: 1787

Answers (2)

Amir
Amir

Reputation: 9637

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

Upvotes: 2

Corey Adler
Corey Adler

Reputation: 16149

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>

Upvotes: 1

Related Questions