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

后端 未结 3 1634
北恋
北恋 2021-01-22 09:44

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.w         


        
相关标签:
3条回答
  • 2021-01-22 10:33

    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" />

    0 讨论(0)
  • 2021-01-22 10:46

    You should try this

     $("#contactname").keypress(function(event){
            var inputValue = event.charCode;
            if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)){
                event.preventDefault();
            }
     });
    
    0 讨论(0)
  • 2021-01-22 10:50

    I finally got solution for this issue

    $("#contactname").keypress(function(e) {
           if (e.which === 32 && !this.value.length) {
               e.preventDefault();
           }
           var inputValue = event.charCode;
           if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)){
               event.preventDefault();
           }          
       });
    

    This code working fine for my exact need

    0 讨论(0)
提交回复
热议问题