Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not allow space as a first character and allow only letters using jquery

Tags:

html

jquery

Im using jquery for the name validation I have tried a code which is given below

$("#contactname").keypress(function(e) {
    if(e.which < 97 /* a */ || e.which > 122 && (e.which < 65 || e.which > 90)) {
       e.preventDefault();
    }         
});

The above code is working fine to allow only letters and not allow numbers but its not allow space.So what i want is it should allow only letters (both small and capital letters) then it should not allow numbers and special characters and also accept space except as a first character And please tell me how to restrict when copy paste.

like image 317
VinoCoder Avatar asked Sep 14 '25 12:09

VinoCoder


2 Answers

Can you use the HTML5 attribute pattern? See the MDN article on it for more information.

Using a regex of ^[a-zA-Z][\sa-zA-Z]* seems to cover your requirements.

So something like:

<div>Username:</div>
<input type="text" pattern="^[a-zA-Z][\sa-zA-Z]*" title="Can use upper and lower letters, and spaces but must not start with a space" />
like image 97
flygaio Avatar answered Sep 16 '25 01:09

flygaio


You should try this

 $("#contactname").keypress(function(event){
        var inputValue = event.charCode;
        if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)){
            event.preventDefault();
        }
 });
like image 42
Manoj Avatar answered Sep 16 '25 01:09

Manoj