I wonder what seems to be the problem in here.
$("#city_field").bind({
keypress: function(event){
var regex = /^[a-zA-ZäöüÄÖÜ]/;
if (regex.test($("#city_field").val())==true) {
$('.r_validation').html('').css('background-color', '');
} else {
$('.validation').html("TEST").css('background-color', 'red');
}
}
});
Whenever I input letters it is valid, then when I input numbers the red validation notice appears. Everything is fine at this point, not until I entered numbers after letters. The following should be invalid, but in my current script it is seen as valid:
- foo1212
- foo,
- foo, [with space after comma]
What I really want to validate is to ONLY accept letters and dash (-), nothing more other than that.
Thanks.
EDIT
For the record, the last comment of @Adam Rackis solved the issue, I ended up with this working code.
$(function(){
$("#city_field").bind("keyup",
function(event) {
var regex = /^[a-zA-ZäöüÄÖÜ]+$/;
if (regex.test($("#city_field").val())==true) {
$('.validation').html('').css('background-color', '');
} else {
$('.validation').html("TEST").css('background-color', 'red');
}
});
});
Your regex is matching only one character. You need to put that input over a Kleene closure, then put an end of string marker:
Or if you want to make sure there’s at least one character, you’d use the positive closure:
Which produces:
DEMO
ALSO, make sure you catch the
keyupevent, sincekeypressfires before the text in your textbox updates, so you’re always validating one character behind.So on your Regex:
When testing
Foo123theFwould be consumed, and that’s it. Done.