Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
186
rated 0 times [  189] [ 3]  / answers: 1 / hits: 37669  / 8 Years ago, mon, may 30, 2016, 12:00:00

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!


More From » jquery

 Answers
17

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


[#61958] Sunday, May 29, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckinleykeyshawnb

Total Points: 281
Total Questions: 99
Total Answers: 111

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;