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
You can use a regular expression to restrict the comma character and accept other characters. Here’s how you can do it in JavaScript:
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.
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
With your current character set of:
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