Allow only numbers and letters to input string

19,971

Solution 1

Would tell you may miss event parameter ?

Without jQuery works like this for me in 3 browsers:

function clsAlphaNoOnly (e) {  // Accept only alpha numerics, no special characters 
    var regex = new RegExp("^[a-zA-Z0-9 ]+$");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (regex.test(str)) {
        return true;
    }

    e.preventDefault();
    return false;
}
function clsAlphaNoOnly2 () {  // Accept only alpha numerics, no special characters 
    return clsAlphaNoOnly (this.event); // window.event
}
<input type="text" id="input" onkeypress="clsAlphaNoOnly(event)" onpaste="return false;">
<input type="text" id="input" onkeypress="clsAlphaNoOnly2()" onpaste="return false;">

Solution 2

One way of validation is using pattern attribute on input element

MDN: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation#Validating_against_a_regular_expression

In your case:

<input type="text" pattern="[a-zA-Z0-9]*">
Share:
19,971

Related videos on Youtube

Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm trying to avoid input of any marks except numbers and letters with input string on my page.php:

    <input type="text" id="input"> 
    

    From this answer only allow English characters and numbers for text input <input type="text" id="input" class="clsAlphaNoOnly"> :

    $(document).ready(function () {
      $('.clsAlphaNoOnly').keypress(function (e) {  // Accept only alpha numerics, no special characters 
            var regex = new RegExp("^[a-zA-Z0-9 ]+$");
            var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
            if (regex.test(str)) {
                return true;
            }
    
            e.preventDefault();
            return false;
        }); 
    })
    

    or this:

    $(function(){
        $("#input").keypress(function(event){
            var ew = event.which;
            if(ew == 32)
                return true;
            if(48 <= ew && ew <= 57)
                return true;
            if(65 <= ew && ew <= 90)
                return true;
            if(97 <= ew && ew <= 122)
                return true;
            return false;
        });
    });
    

    in both cases string is clear, but I'm using two types of input with button click $("#btn").click(function() to process input and $(document).keypress(function(e) with hit on enter key on keyboard for same input. By some reason if I include this methods to avoid extra marks in string, pressing on enter key does not allows to input inserted value.

    This way works fine:

    <input type="text" id="input"  onkeypress="return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode >= 48 && event.charCode <= 57)" />
    

    but I want avoid extra code with html in page.php. I'm trying to figure out, what causes blocking of entering for inserted value with given methods

    • epascarello
      epascarello over 4 years
      well enter is key 13 and you are not allowing it and code can be bypassed with paste.
  • Wiktor Stribiżew
    Wiktor Stribiżew over 4 years
    FYI, pattern="^[a-zA-Z0-9]+$" = pattern="[a-zA-Z0-9]+" as the latter is transated into a ^(?:[a-zA-Z0-9]+)$ pattern.
  • Get Off My Lawn
    Get Off My Lawn over 4 years
    Thanks, I have changed it.
  • Tom
    Tom over 4 years
    Or check console your log for errors, btw pattern does not exist in IE.
  • Admin
    Admin over 4 years
    Hello, sure this way good with "required" as alert for incorrect text, but I have to clean typed text for input
  • Admin
    Admin over 4 years
    @Get Off My Lawn Hello, yes I've missed to note that I have to clean typed text for input, because pattern would be useful only for "required" alert, but will allow marks to string in textbox
  • Tom
    Tom over 4 years
    There should be some onpaste fix, but for simplicity blocked it according to stackoverflow.com/questions/1226574/…
  • Sophie
    Sophie over 2 years
    Hey, how can I use your example with regex? the example above use regex but needs a function onkeypress inside input...
  • Adnane Ar
    Adnane Ar over 2 years
    Hey @Sophie, actually you don't need my example to validate a simple regex.
  • Adnane Ar
    Adnane Ar over 2 years
    Hello again @Sophie, I have made this codepen for your to make get your a better solution for your problem codepen.io/adnane-ar/pen/gOGdvdY
  • Sophie
    Sophie over 2 years
    Hey @Adnane I dont want to validate a phone number, I want to use this regex: "[A-Za-záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ ]" with the same model as your code, using addEventListener
  • Adnane Ar
    Adnane Ar over 2 years
    Hi @Sophie, then why not just add/append your záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ to the allowedCharacters string and that would do it.
  • Sophie
    Sophie over 2 years
    Hey adnane, using this not permit the accents =/ could you help me out?
  • Adnane Ar
    Adnane Ar over 2 years
    @Sophie, sure can you please provide me with your code just so I could read it and see where to do the magic!
  • Sophie
    Sophie over 2 years
    Hey Adnane, heres the pen codepen.io/sophiehf35/pen/NWaEWbr
  • Adnane Ar
    Adnane Ar over 2 years
    @Sophie, paste.pics/FM7RV did you try to do it that way?
  • Sophie
    Sophie over 2 years
    Dam.. so the point is just insert in the end... haha thanks
  • Adnane Ar
    Adnane Ar over 2 years
    @Sophie, you're welcome, have a great day!
  • Sophie
    Sophie over 2 years
    you too hehe thank you soo much for your attenction =]
  • Adnane Ar
    Adnane Ar over 2 years
    @Sophie, I inviter you to take a look at the modern version. I have edited the current answer to a perfect example for you!
  • Sophie
    Sophie over 2 years
    nice your code is shorter then mine :O
  • Sophie
    Sophie over 2 years