5

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

5 Answers5

6

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;">
Jan
  • 2,178
  • 3
  • 14
  • 26
  • Or check console your log for errors, btw pattern does not exist in IE. – Jan Aug 28 '19 at 18:35
  • There should be some onpaste fix, but for simplicity blocked it according to https://stackoverflow.com/questions/1226574/disable-pasting-text-into-html-form#1723838 – Jan Aug 29 '19 at 08:04
4

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]*">
Chiffie
  • 581
  • 3
  • 18
  • 1
    Hello, sure this way good with "required" as alert for incorrect text, but I have to clean typed text for input –  Aug 28 '19 at 18:41
1

If you really do not want to use the Regex method as the comments bellow advice you, then you can use this simple code :

document.querySelector("input#testInput").addEventListener("input", function(){
  const allowedCharacters="0123456789azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBNzáàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ "; // You can add any other character in the same way
  
  this.value = this.value.split('').filter(char => allowedCharacters.includes(char)).join('')
});
<input type="text" id="testInput">
Adnane Ar
  • 683
  • 7
  • 11
  • Hey, how can I use your example with regex? the example above use regex but needs a function onkeypress inside input... – Sophie Jan 09 '22 at 03:02
  • Hey @Sophie, actually you don't need my example to validate a simple regex. – Adnane Ar Jan 09 '22 at 15:20
  • Hello again @Sophie, I have made this codepen for your to make get your a better solution for your problem https://codepen.io/adnane-ar/pen/gOGdvdY – Adnane Ar Jan 09 '22 at 16:12
  • 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 – Sophie Jan 09 '22 at 19:22
  • 1
    Hi @Sophie, then why not just add/append your `záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ` to the `allowedCharacters` string and that would do it. – Adnane Ar Jan 11 '22 at 16:16
  • Hey adnane, using this not permit the accents =/ could you help me out? – Sophie Jan 11 '22 at 19:51
  • @Sophie, sure can you please provide me with your code just so I could read it and see where to do the magic! – Adnane Ar Jan 11 '22 at 20:04
  • Hey Adnane, heres the pen https://codepen.io/sophiehf35/pen/NWaEWbr – Sophie Jan 11 '22 at 20:15
  • @Sophie, https://paste.pics/FM7RV did you try to do it that way? – Adnane Ar Jan 11 '22 at 20:22
  • Dam.. so the point is just insert in the end... haha thanks – Sophie Jan 11 '22 at 20:25
  • @Sophie, you're welcome, have a great day! – Adnane Ar Jan 11 '22 at 20:27
  • you too hehe thank you soo much for your attenction =] – Sophie Jan 11 '22 at 20:29
  • 1
    @Sophie, I inviter you to take a look at the modern version. I have edited the current answer to a perfect example for you! – Adnane Ar Jan 11 '22 at 20:39
  • nice your code is shorter then mine :O – Sophie Jan 11 '22 at 20:47
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/240970/discussion-between-sophie-and-adnane-ar). – Sophie Jan 11 '22 at 20:50
0

Instead of javascript you could use a pattern along with required. pattern will allow you to specify a required pattern for the input, and required will make the input required. Both must evaluate to true in order for the form to submit.

<form>
  <input type="text" id="input" pattern="[a-zA-Z0-9]+" required> 
  <input type="submit">
</form>
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • 2
    FYI, `pattern="^[a-zA-Z0-9]+$"` = `pattern="[a-zA-Z0-9]+"` as the latter is transated into a `^(?:[a-zA-Z0-9]+)$` pattern. – Wiktor Stribiżew Aug 28 '19 at 18:26
  • Thanks, I have changed it. – Get Off My Lawn Aug 28 '19 at 18:28
  • @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 –  Aug 28 '19 at 18:43
0

HTML Input Way :

1- Simple HTML5 Input

<input type="text" pattern="[a-zA-Z0-9]*">

2- Inline Function

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


Jquery Way :

$('#ID').on('keypress', function (e) { var code = ('charCode' in e) ? e.charCode : e.keyCode; if (!(code > 47 && code < 58) && !(code > 64 && code < 91) && !(code > 96 && code < 123)) {e.preventDefault();}});


Javascript Function :

function allowAlphaNumericSpace(e) {
  var code = ('charCode' in e) ? e.charCode : e.keyCode;
  if ( !(code > 47 && code < 58) && !(code > 64 && code < 91) && !(code > 96 && code < 123)) { e.preventDefault();}};

<input type="text" onkeypress="allowAlphaNumeric(event)" />
KRISHNA
  • 189
  • 3
  • 8