2

I'm using this code to prevent people from puting spaces between alphabets and numbers. I would lilke to modify the code so that only alphabets, letters and numbers can be typed.

This is what i'm doing:

 replace(/\sg, '') oin javascript

Can anyone help me as to how to costrucrt the regex expression so that only alphavets, nnumbers, underscore and no space can be keyed in the input box

Thanks

2
  • Have you tried to learn how to compose regular expressions? Commented Aug 26, 2013 at 1:33
  • Please, take a look at the update here. Commented Aug 26, 2013 at 3:53

2 Answers 2

4

Here's how you could do it with jQuery:

$(function() {
    $( '#username' ).on( 'keydown', function( e ) {
        if( !$( this ).data( "value" ) )
             $( this ).data( "value", this.value );
    });
    $( '#username' ).on( 'keyup', function( e ) {
        if (!/^[_0-9a-z]*$/i.test(this.value))
            this.value = $( this ).data( "value" );
        else
            $( this ).data( "value", null );
    });
});

SQL Fiddle Demo

Sign up to request clarification or add additional context in comments.

1 Comment

this is good, but if you hold the space bar or a character key down, you can get past it and it wont prevent characters from being entered...out of curiosity is there a way to prevent that?
2

Perhaps you want something like this:

var input = "f%o@o";
var output = input.replace(/\W/g, ''); // "foo"

This will remove any non-word character (a word character is a letter, number, or underscore) from the input string.

4 Comments

I actually just want leters, numbers and unserscore to be in the input. So I guess the opposite
@KwaasiDjin That's what this will do. It will remove non-word characters.
yeah but this includes symbolds like @#$%^&*, however, i just want underscore letters and numbers
@KwaasiDjin Please see the example. "f%o@o".replace(/\W/g, '') becomes "foo".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.