skip to Main Content

I have a regex input pattern as below: [0-9A-Za-z!-/:-@[-`{-~] and my limit to input is 1, here currently it is accepting comma , I need to avoid accepting commas. what will be my input pattern

I tried something like this [^,]+[0-9A-Za-z!-/:-@[-`{-~] but it is not accepting other characters now

3

Answers


  1. You can use a regular expression to restrict the comma character and accept other characters. Here’s how you can do it in JavaScript:

    const inputBox = document.querySelector('#inputBox');
    
    inputBox.addEventListener('input', function(e) {
      const regex = /^[^,]{0,1}$/;
      if (!regex.test(e.target.value)) {
        e.target.value = e.target.value.substring(0, e.target.value.length - 1);
      }
    });

    In this code, inputBox is assumed to be the ID of your input element. The input event listener is added to the input box. The regular expression ^[^,]{0,1}$ matches any string of length 0 or 1 that does not contain a comma. If the input does not match this regular expression, the last character of the input is removed.

    Please replace #inputBox with the actual ID of your input element.

    Login or Signup to reply.
  2. Please refer to the below ascii table, I limited the ranges so that comma alone gets excluded!

    • ! to + will get included

    • after which comma has been excluded

    • – to : will get included

    I have used the escape key wherever needed!

    Ascii Table

    [0-9A-Za-z!-+--/:-@[-`{-~]
    
    Login or Signup to reply.
  3. With your current character set of:

    [0-9A-Za-z!-/:-@[-`{-~]
    

    You’re using the range of !-/, which includes characters of ASCII codes between 31 and 47, which includes the comma ,, of ASCII code 44.

    Since the character set includes all printable ASCII characters and you want to exclude the comma, you can include two ranges from ASCII codes 33 (!) to 43 (+) and from 45 (-) to 126 (~) instead:

    [!-+--~]
    

    Demo: https://regex101.com/r/4R1TJ9/1

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search