This.Sven This.Sven - 6 months ago 15
jQuery Question

JavaScript input validation with regex

I want to validate my inputs, so the user, can just enter letters. The problem I've is, that it does just checks one input field but I selected all with

:input


code:

$('#formularID').submit(function() {
var allInputs = $(":input").val();
var regex = new RegExp("[a-zA-Z]");
if(regex.test(allInputs)) {
alert("true");
}else {
alert("false");
return false;
}


I appreciate every help I can get!

Answer

Firstly you need to cycle through each of your input elements, you can do this by using .each():

// Cycles through each input element
$(":input").each(function(){
    var input = $(this).val();
    ...
});

Next your RegExp is only checking for the first character to be a letter, if you want to ensure that only a steam of letters can match you will want to use ^[a-zA-Z]+$ instead:

$(":input").each(function(){
    var input = $(this).val();
    var regex = new RegExp("^[a-zA-Z]+$");
    if(regex.test(input)) {
        alert("true");
    }else {
        alert("false");
        return false;
    }
});

Here is an example Fiddle

Comments