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:
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 ment 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');
}
});
});
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:
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 ment 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:
/^[a-zA-ZäöüÄÖÜ]*$/;
Or if you want to make sure there's at least one character, you'd use the positive closure:
/^[a-zA-ZäöüÄÖÜ]+$/;
Which produces:
var r = /^[a-zA-ZäöüÄÖÜ]+$/;
console.log(r.test('Foo')); //true
console.log(r.test('Foo123')); //false
console.log(r.test('foo,')); //false
console.log(r.test('foo, ')); //false
console.log(r.test('foo ')); //false
DEMO
ALSO, make sure you catch the keyup
event, since keypress
fires before the text in your textbox updates, so you're always validating one character behind.
So on your Regex:
/^[a-zA-ZäöüÄÖÜ]/;
When testing Foo123
the F
would be consumed, and that's it. Done.