Reputation: 1698
I have form where a user can add more input boxes on button click. User can have as much input boxes as they want.
I do not plan to add a button for removing fields.
They default number of input boxes is 2. Say the user decides to add 3 more, now there are a total of 5.
For validation, I would like to check if the input box is empty or if the input has all spaces like: " " no matter how many spaces as long as it has nothing else but space. I can do the check for an empty input by checking length, but how can I check for the latter? Is there a regular expression for any number of consecutive spaces? Thanks!
PS: I am using jQuery with jQuery mobile
Upvotes: 0
Views: 248
Reputation: 3903
Your question has a few components:
We need to address all of these issues in a systematic manner:
Starting with the easiest - detecting empty string:
if (value.replace(/\s/g,'')=='') //string is empty
Next, to add input fields dynamically:
var myinput=document.createElement('input');
document.body.appendChild(myinput);
//the trick here is to "remember" this element for later use
document.myinputs=[];
document.myinputs.push(myinput);
To check all your input fields, you check the static ones first, then loop through the dynamic input fields:
valid=true; //default to true unless detected otherwise
for (var i=0;i<document.myinputs.length;i++){
var input=document.myinputs[i];
if (input.value.replace(/\s/g,'')=='') valid=false;
}
alert(valid);
Upvotes: 1
Reputation: 21887
You can check if an input field is blank by checking its .value.length
, as you already know. To check if it only contains whitespace, then try this: (assuming that the input is stored in a variable called input
)
if (!input.value.trim().length) // oh noes! it's blank or whitespace-filled!
Upvotes: 1