-1

I am trying to prevent user from entering special character like (!,@,&)

Following code restrict user to enter above character only if it is first character after that it allows user to enter above character.

for example & can not be entered but A& can be entered

$('input#first_name-required').bind('keypress', function(e) {
    console.log( e.which );
    if($('input#first_name-required').val().length == 0){
        var k = e.which;
        var ok = k >= 65 && k <= 90 || // A-Z
            k >= 97 && k <= 122 || // a-z
            k >= 48 && k <= 57 //0-9 ;

        if (!ok){
            e.preventDefault();
        }
    }
}); 
Aditya Joshi
  • 245
  • 4
  • 12
  • You can check out this : https://stackoverflow.com/questions/4444477/how-to-tell-if-a-string-contains-a-certain-character-in-javascript – gavsta707 Jun 29 '17 at 20:56
  • If you want it to work for all characters and not just the first, why do you have this condition: `if($('input#first_name-required').val().length == 0){` ? It seems like you're very specifically telling it to only check the first character. – Tyler Roper Jun 29 '17 at 20:57
  • 1
    Please note that you shouldn't rely on this for any security, all checks should also be done on the server side. – Maya Jun 29 '17 at 21:03

2 Answers2

2
if($('input#first_name-required').val().length == 0)

Just remove this condition and it should work fine.

.val() returns the string inside of the input. .length == 0 practically means "if the string is 0 characters long". You validation only runs when the input is empty, thus only when you type the first character.

Freeman Lambda
  • 3,567
  • 1
  • 25
  • 33
1

You have added if condition. I think you might want to check for length grater than 0

$('input#first_name-required').bind('keypress', function(e) {
    
    
        var k = e.which;
        var ok = k >= 65 && k <= 90 || // A-Z
            k >= 97 && k <= 122 || // a-z
            k >= 48 && k <= 57 //0-9 ;

        if (!ok){
            e.preventDefault();
        }
    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="first_name-required">
Omi
  • 3,954
  • 5
  • 21
  • 41