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!
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!
Share Improve this question edited May 31, 2016 at 0:57 Mark Chackerian 23.6k6 gold badges114 silver badges105 bronze badges asked May 30, 2016 at 22:36 user5616242user5616242 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. – Casimir et Hippolyte 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()
. – Spencer Wieczorek 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 – user5616242 Commented May 30, 2016 at 22:46
1 Answer
Reset to default 10Firstly 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