tags:

views:

112

answers:

1

Without using jQuery, what is the best way to limit text entry of a textbox to numbers, lowercase letters and a given set of symbols (for example - and _)? If the user enters an uppercase letter, I would like it to be automatically converted to a lowercase letter, and if the user enters a symbol not within the given set, I would like to be able to instantly show a validation error (show some element adjacent to or below the text box).

What's the cleanest cross-browser way of doing this without the aid of jQuery?

+1  A: 

Attach the following to your elements onkeyup event.

function onkeyup() 
{
    var el = document.getElementById("id"); // or however you want to get it

    el.value = el.value.toLowerCase(); // covert to lower case

    if (el.value.match(/[^-\d\w]/)) // check for illegal characters
    {
        // show validation error
        ...
        // remove invalid characters
        el.value = el.value.replace(/[^-\d\w]/g, "");
    }
    else
    {
        // hide validation error
    }
}

The regex matches any character which is not a digit, a letter, a hyphen or an underscore.

Joel Potter
If you are going to do this with multiple inputs, it would be a good idea to create a plugin http://docs.jquery.com/Plugins/Authoring
caligoanimus
There's already a plugin for that. It's called Jquery Validation. But the OP doesn't want to use a framework.
Joel Potter
This solution doesn't prevent users from entering illegal characters, it only alerts them when the input is invalid. Is there a way to drop the illegal character so that it simply can't be typed in the text box? Also, will this work with such things as pasting into the field?
Adam Maras
@Adam, I read your question as wanting to show a validation error. To prevent the character getting entered, you would either have to use the keydown event and `return false` or do a regex replace at the same place it shows the validation error. See my edit.
Joel Potter
Beautiful, thank you.
Adam Maras