views:

45

answers:

1

I have a text box that I would like to do some validation on. At the moment I have this code:

function updateChanger() {

    // Validate input
    var likeMessage = validateInput($("#like").val());

    alert(likeMessage);
}

function validateInput(input) {
    input = input.replace(/[^a-zA-Z0-9:\(\/\)\s\.,!~]/g, "");
    return input;
}

This successfully trims out unwanted characters in the likeMessage variable, but the character still gets entered into the text box. I would like to stop that from happening.

I know it will have something to do with $("#like").val() but the only thing I can think of is just chopping off the end character from the text box value, would this suffice?

Thanks for any help!

+3  A: 

You can do it using the keyup event, like this:

$("#like").keyup(function() {
  $(this).val($(this).val().replace(/[^a-zA-Z0-9:\(\/\)\s\.,!~]/g, ""));
});

This checks for and removes invalid characters every time they key lets up, so the invalid character won't ever be left in the box, it gets removed immediately.

Nick Craver
Ah, perfect! It'll only let me accept your answer in about 9 minutes though :) Thanks!
VIVA LA NWO