apoorv sharma
apoorv sharma

Reputation: 1

Regex which allows alphanumeric character and only single "-"

I need to prevent user input of the following characters into input fields

~!#$%^&*()+/\"'`:;{}[]|<>=–

Take note that the is 2 consecutive -

I have tried ^[a-z ]+([-])[a-z ]

Upvotes: 0

Views: 64

Answers (1)

Carsten Massmann
Carsten Massmann

Reputation: 28236

Here is variation of @Rohan's/@mplungjan's answer. As the validation will be done at submit time the typing of more than one "-" will not be prevented while you are typing.

<form onsubmit="return false">
  <input type="text" pattern="^[\w\s]*-?[\w\s]*$" title="Only letters, numbers, whitespaces and one '-' are allowed">
  <input type="submit" />
</form>

Here is another JavaScript-based version, that will quietly remove any of the unwanted characters:

const pattern=/^[\w\s]*-?[\w\s]*$/
document.querySelector("input").addEventListener("input",ev=>{
 ev.target.value=ev.target.value.replace(/[^a-zA-Z0-9 -]/g,"").replace(/-(?=.*-)/,"")
})
<form onsubmit="return false">
  <input type="text">
  <input type="submit" />
</form>

Upvotes: 1

Related Questions