6

I want to validate my inputs, so the user can just enter letters. The problem is that it 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!

3
  • When you want to test a whole string, you must describe a whole string (and not only one character). But you can do it in another way, if you build a pattern that must not match the subject (for example using a negated character class with forbidden characters). In this case, you only need to test if the pattern fails and one character suffices. Commented May 30, 2016 at 22:38
  • Use the .each() to cycle through each input element, you are only getting/testing the value of the first one by doing $(":input").val(). Commented May 30, 2016 at 22:39
  • thanks for the fast replies! @Casimir et Hippolyte - You're right, I used ! and just checked whether the pattern fails. And @Spencer Wieczorek - (I don't know whether I can do that ) I used $(":input").val().each() but then he does just submit the form without checking the value Commented May 30, 2016 at 22:46

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

I can't thank you enough! Finally he does check all my inputs!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.