Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

validation - jquery - validate characters on keypress?

I have a form text field that I want to allow only numbers and letters in. (i.e., no #$!, etc...) Is there a way to throw up an error and prevent the keypress from actually outputting anything if the user tries to use any character other than numbers and letters? I've been trying to find a plugin, but haven't really found anything that does this...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$('input').keyup(function() {
    var $th = $(this);
    $th.val( $th.val().replace(/[^a-zA-Z0-9]/g, function(str) { alert('You typed " ' + str + ' ".

Please use only letters and numbers.'); return ''; } ) );
});

EDIT:

There are some other good answers here that will prevent the input from taking place.

I've updated mine since you also wanted to show an error. The replace can take a function instead of a string. The function runs and returns a replacement value. I've added an alert to show the error.

http://jsfiddle.net/ntywf/2/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...