1

Background Information:

I have a form that includes a field called "phone number". When the user types in a number, to prove that it's valid, I do a look up and return any matching country codes based on a certain algorhythm. The question is which event should I use to trigger this lookup / validation. Right now, I have it triggering on the .change event, which is mostly ok, except when the field in question is the LAST field on the page. The users are not noticing the fact that it does a lookup.

Code:

$( "#phone_num" ).change(function() {
    $("#ratecenter").html('');  
    var pstn = $(this).val();
    if (validphonenumber(pstn)) {
            var query_data = {pstn_number: pstn,action:"find_ratecenter" };
            $.ajax({
            url: "/cgi-bin/phonenumbers",
            dataType: "json",
            data: query_data,
            success: function(data) {
                $("#ratecenter").html(data[0].ratecenter);              
              }
            });//end ajax
    } else {
        $("#results").html("Invalid phonenumber. Please enter a '+' followed by a min of 7 / max of 15 numbers");
        return false; 
    }
});

Assuming that I cannot change where this field appears on the form, can you suggest a better way to do this validation? When they click on submit, I'm repeating the same validation logic so they can't get around it... But it'd be nice to be able to "inform" them before the attempt to submit the data

dot
  • 14,928
  • 41
  • 110
  • 218

3 Answers3

1

You can use the input event which works pretty well for textboxes / input boxes and the event is triggered every time something is typed.

Shakti Phartiyal
  • 6,156
  • 3
  • 25
  • 46
1

use

$(element).bind('input propertychange', function() {
  //do stuff
});

Take a look at the following question for how to validate input while it is typed as opposed to after leaving the input field.

Validate html text input as it's typed

Community
  • 1
  • 1
Our_Benefactors
  • 3,220
  • 3
  • 21
  • 27
1

You can do it on 'keyup' and it's going to be validated as the phone number is being introduced.

$("#phone_num").on('keyup', function() {
   // your validation
});
Ju Oliveira
  • 428
  • 8
  • 14