I am trying to disable input of certain values using jQuery and regex via typed or pasted input (anything that isn't alphanumeric or a hyphen should return false and e.preventDefault()
is called to stop input). Every time I run this test it fails by returning false no matter what the input is and I can't figure out what I'm doing wrong here.
When I run the test in node console valid.test("hello-world")
(or a variable equal to "hello-world") it comes back as true, and when I do valid.test("hello_world")
it comes back as false, but when I do it using my code below it comes back as false every time no matter the input.
My code:
jQuery('#input').on('keydown paste', function(e) {
var input = e.target.value;
var isValid = /^[a-zA-Z\d-]+$/;
var tester = isValid.test(input);
if (tester === false) {
e.preventDefault();
console.log("Input allowed? " + tester);
} else if (tester) {
console.log("Input allowed? " + tester);
}
});
In node console I get the following results:
"hello-world" = true
"hello_world" = false
"hello." > false
"goodness gracious" = false
"goodness-gracious" = true
"goodness123" = true
"goodness!!" = false
What am I missing here?
EDIT: I created a codepen to show the result I'm getting: https://codepen.io/anon/pen/JpdMgM