I have the following javascript that does not allow the user to input any special characters into a field, but I do want to make an exception and allow for a dash (-):
function Validate(txt)
{
txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r]+/g, '');
}
How to modify it to add the dash to the allowed list?
To allow the dash (
-), all you need to do is to change this:txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r]+/g, '');to this:txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r-]+/g, '');.Note that the dash is a special character when enclosed within the square brackets (it denotes a range) so it must be places last within the square brackets.
As per @Tim Pietzcker‘s comment, you can also escape it
txt.value = txt.value.replace(/[^a-zA-Z 0-9\n\r\-]+/g, '');or put it at the front:txt.value = txt.value.replace(/[^-a-zA-Z 0-9\n\r]+/g, '');.