views:

241

answers:

2

What would be the easiest way to allow only letters/numbers in a textbox. We are using JS/jQuery, but don't want to use a validation plugin?

+2  A: 

If you don't wanna use plugins - What about some plain old JS validation?

I posted about this on my blog a while ago --> http://dotnetbutchering.blogspot.com/2009/04/definitive-javascript-validation-with.html

You'll see that the function in my proposed solution takes a input field ID and a regex (and you'll have to come up with a regEx for your validation needs, should be pretty trivial if you want only aplhanumeric) and sets the background of the control to green or red depending on the outcome of the validation. I know it's not perfect but I think it's enough to get you going, and you can use it as a starting point to roll your own.

I am sure there are mote elegant solutions using jQuery or plain JS but something along these lines has been working pretty well for me so far.

Hope it helps.

JohnIdol
+2  A: 

You can use a simple regex on form submit to evaluate the contents of the text box, show an error, and stop the form submit. Make a function out of the check and you can also apply it when the text box loses focus. Do this very often and you'll find that you've reimplemented the validation plugin.

$(function() {
    $('form').submit( function() {
        return validateTB( $('#textbox'), true, $('#textboxError') );
    });

    $('#textbox').blur( function() {
        validateTB( $(this), true, $('#textboxError') );
    });

    function validateTB(tb,required,msg) {
        var $tb = $(tb);
        var re = '/^[a-z0-9]';
        if (required) {
           re += '+';
        }
        else {
           re += '*';
        }
        re += '$/';

        if ($tb.val().match(re) == null) {
           $(msg).show();
           return false;
        }
        $(msg).hide();
        return true;
    }
});
tvanfosson
+1 --> nice snippet
JohnIdol