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 ]
CodePudding user response:
You can use a regular expression to prevent the user from entering certain characters. To prevent the characters you listed, you can use the following regular expression pattern:
^[a-zA-Z0-9\s] $
This pattern only allows letters (uppercase and lowercase), numbers, and whitespace characters (spaces, tabs, etc.). All other characters will be rejected by this pattern.
You can use this pattern in an HTML input field using the pattern attribute and also a title attribute to show a message when user enters invalid characters.
<form onsubmit="return false">
<input type="text" pattern="^[a-zA-Z0-9\s] $" title="Only letters, numbers and whitespace are allowed">
<input type="submit" />
</form>
Alternatively, you can also use a JavaScript function to check the input value before it is submitted and show an error message when you submit if the input contains any invalid characters
function validateInput(input) {
var pattern = /[~!#$%^&*() \/\"'`:;{}[]|<>=–]/;
if(pattern.test(input)) {
alert("Invalid characters entered!");
return false;
}
return true;
}
You can call this function on the onchange event of the input field
<input type="text" onchange="validateInput(this.value)" >
This way it will check the input value before user submits the form and will show an error message if invalid characters are found.
CodePudding user response:
Here is variation of @mplungian'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>