views:

30

answers:

2

I have textbox whose value if entered needs to be validated using some regularexpression I need to validate the value as user is entering the data. Which is suitable event can be used for this ? some sample example of using onfocus event on textbox will be helpful

A: 

Use onKeypress or onKeyup. Beginners often think that onChange will do what you want, but that only fires when the input loses the focus. OnFocus is irrelevant - that is when the box first gets the focus, not when the user types.

Colin Fine
A: 

Typically you would do this when the text input loses focus, so it would be using the blur event. The reason is that many inputs aren't valid until some sufficient number of characters has been typed. It can be very annoying to the user to put up a validation error while they are still typing a valid string. For example, when doing email validation, the input cannot be valid until the @ sign has been entered. Note that you'd also need to validate when the form is submitted to catch the case where the field has never had focus.

Using jQuery it might look like:

 $('.klass').blur( function() {
     if (!$(this).val().match( /your-regular-expression/ )) {
         $(this).next('.validation-message').show();
         return false;  // keep focus on field
     }
     return true;
 });

This assumes some HTML like

 <input type="text" class="klass" name="myInput" />
 <span class="validation-message" style="display: none;">This is not valid</span>
tvanfosson

related questions