How do I get the iterated id value for form validation in Javascript?

Hi everybody!

I have a form in which I have a for-loop in php to generate multiple text fields. Since I need to validate(regex) the input fields, I do not know how to use the document.getElementById('textfield<?php echo $i; ?>').

I know this is wrong, and I may need to get something like getElementById('textfield'+$i) ... I have tried a lot but I am an absolute beginner in Javascript and so am clueless!!!

Do I also need to use a for loop in the javascript file to generate the $i or something????

I do know that I do not want to get all the fields together by using:
getElementById() OR getElementsByTagName() and then validate whether they are empty fields by clicking onsubmit().

I need to check each input against a specific regex pattern so I need to isolate the value of each iterated id so I do the regex checking.

Can anyone help me please?

Thanks in advance!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
  <p>
    <?php 
for ($i=1;$i<=3;$i++){
?>
        <input type="text" name="textfield<?php echo $i; ?>" id="textfield<?php echo $i; ?>" />
    </br>
  <?php  } ?>
  </p>
  <p>
    <input type="submit" name="button" id="button" value="Submit" />
  </p>
</form>
</body>
</html>

Open in new window

forumPosting.php
786aslamkhanAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
Julian HansenConnect With a Mentor Commented:
Please take a look at the code below. No time to comment - there were several things wrong with your code but this gives an example of what I think you were trying to achieve.
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function producePrompt(message,promptLocation,color)
{
  document.getElementById(promptLocation).innerHTML=message;
  document.getElementById(promptLocation).style.color=color;
}


function validate()
{
 // GET ALL INPUT ELEMENTS INTO AN ARRAY
  var inps=document.getElementsByTagName("input");
  // SAMPLE VALIDATION - ONLY ALLOWS DIGITS
  var regx = /^[a-zA-Z0-9]+$/;
	
	 // LOOP THROUGH ALL ITEMS IN ARRAY
  for(i = 0; i < inps.length; i++) {
 
    // If this is a submit button then ignore it.
    if (inps[i].type == 'submit' ) continue;
	producePrompt("", "txtfield" + (i+1) + "_prompt", "");
	if (!regx.test(inps[i].value)){
      producePrompt("'Alphanumeric data only! ","txtfield" + (i+1) + "_prompt","red");
      return false;
	}

    // TEST THE VALUE OF THE FIELD AGAINST OUR REGX
    if (!regx.test(inps[i].value)) {
      // SHOW THE ERROR
     // alert('failed validation for ' + inps[i].value);
	
      // RETURN FALSE TO TELL THE FORM NOT TO SUBMT
      return false;
    }
  }
  return false;
}

function alphaNum(evt)
{
	this.value = 'fred';
}		

</script>
<title>Untitled Document</title>
</head>

<body>
<form id="form1" name="form1" method="post" onsubmit="validate(); return false;">
 <div id="inputFields">
    
   <label id="txtfield_prompt" class="style27"> </label><br />
  
<?php 
for ($i=1;$i<=3;$i++) :
?>
    
    <input type="text" name="textfield<?php echo $i; ?>" id="textfield<?php echo $i; ?>" onkeyup="this.value=this.value.replace(/[^a-zA-Z0-9]/g, '')"/><div class="prompt" id="txtfield<?php echo $i;?>_prompt"></div>
    <br/>
	
<?php
endfor 
?>
  </div>
  <p>
    <input type="submit" name="button" id="button" value="Submit" />
    <input type="reset" name="button2" id="button2" value="Reset" />
  </p>
</form>
</body>
</html>

Open in new window

0
 
Julian HansenCommented:
Here is some sample code to get you started
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function validate()
{
 // GET ALL INPUT ELEMENTS INTO AN ARRAY
  var inps=document.getElementsByTagName("input");

  // SAMPLE VALIDATION - ONLY ALLOWS DIGITS
  var regx = /[0-9]+/;

  // LOOP THROUGH ALL ITEMS IN ARRAY
  for(i = 0; i < inps.length; i++) {

    // If this is a submit button then ignore it.
    if (inps[i].type == 'submit') continue;

    // TEST THE VALUE OF THE FIELD AGAINST OUR REGX
    if (!regx.test(inps[i].value)) {
      // SHOW THE ERROR
      alert('failed validation for ' + inps[i].value);

      // RETURN FALSE TO TELL THE FORM NOT TO SUBMT
      return false;
    }
  }

  // ALL OK SUBMIT ALLOWED
  return true;
}

</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="" onsubmit="return validate();">
  <p>
    <?php 
for ($i=1;$i<=3;$i++){
?>
        <input type="text" name="textfield<?php echo $i; ?>" id="textfield<?php echo $i; ?>" />
    </br>
  <?php  } ?>
  </p>
  <p>
    <input type="submit" name="button" id="button" value="Submit" />
  </p>
</form>
</body>
</html>
           

Open in new window

The above is provided for illustration purposes. There are validation libraries out there that you could also consider.
0
 
786aslamkhanAuthor Commented:
@julianH: Thank you for reading my question and responding! I'm working on your suggestions and will get back to you as soon as I can. Thank you for your interest and time!

By validation libraries do you mean various posts on various sites or dedicated libraries like jsclasses.org. May I please request you to recommend some? Thanks!
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Julian HansenCommented:
I meant javascript libraries that do form validation for you.

One option is to look at JQuery and the JQuery valiation (http://jqueryvalidation.org/) plugin

If you want to stay with plain javascript here are some links

http://parsleyjs.org/
http://rickharrison.github.io/validate.js/
0
 
786aslamkhanAuthor Commented:
@julianH: Thanks a ton! Very helpful of you! I have noted the links. Thanks!

I'm still working on my solution... Your suggestions have very useful and the code and the approach work. I'm just trying to get a text / message prompt instead of the alert (showing the error). My issue is that the prompt field is also iterated into corresponding label_ids.
0
 
Sar1973Commented:
I'd also suggest to use different names and ids for your objects, and also not to use the name of objects (such as "button") as names and ids.
0
 
786aslamkhanAuthor Commented:
@Sar1973: Thank you for your suggestions. I shall be cautious not to use such names as you have warned me about,  although I have used unique ones so far. Thank you!
0
 
786aslamkhanAuthor Commented:
@julianH:

Your suggestions are very useful and when applied they work perfectly.

My issue, which takes me back to my question is "to check each input against a specific regex pattern so I need to isolate the value of each iterated id so I do the regex checking".

 Also as I have indicated in my earlier post that "I'm just trying to get a text / message prompt instead of the alert (showing the error). My issue is that the prompt field is also iterated into corresponding label_ids. ".

What I'm trying to achieve is the same effect as in the demo in the site (http://jquery.bassistance.de/validate/demo/) that the link you had kindly posted for me (on the top of the page with a lime-green background).

How do we achieve that where the text field has been iterated as in my case (code provided earlier). I have tried everything I could think of with my limited exposure to Javascript and failed!


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script>
function producePrompt(message,promptLocation,color){
		document.getElementById(promptLocation).innerHTML=message;
		document.getElementById(promptLocation).style.color=color;
		}


 function validate()
{
 // GET ALL INPUT ELEMENTS INTO AN ARRAY
 
  var inps=document.getElementsByTagName("input");
  
  // SAMPLE VALIDATION - ONLY ALLOWS DIGITS
  var regx = /^[a-zA-Z0-9]+$/;
	
	 // LOOP THROUGH ALL ITEMS IN ARRAY
  for(i = 0; i < inps.length; i++) {
  
    // If this is a submit button then ignore it.
    if (inps[i].type == 'submit' ) continue;
	
	if (inps[i].length == 0 || inps[i].value == ""){
	
		producePrompt("","txtfield_prompt","red");
			return false;
		}

    // TEST THE VALUE OF THE FIELD AGAINST OUR REGX
    if (!regx.test(inps[i].value)) {
      // SHOW THE ERROR
     // alert('failed validation for ' + inps[i].value);
	
producePrompt("'Alphanumeric data only! ","txtfield_prompt","red");
      // RETURN FALSE TO TELL THE FORM NOT TO SUBMT
      return false;
    }
	if(regx.test(inps[i].value)) {

producePrompt("Valid input","txtfield_prompt","green");
  
      return true;
    }
    }
    }
		
</script>

<!--<form id="someForm" action="#" method="post" onsubmit="return false">
 <span id="inputFields">
  <p>
   <input type="text" name="textfield1"/>
  </p>
  <p>
   <input type="text" name="textfield2"/>
  </p>
  <p>
   <input type="text" name="textfield3"/>
  </p>
 </span>
 <input type="submit" />
</form> -->
<title>Untitled Document</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="" >
 <span id="inputFields"> <p>
    
   <label id="txtfield_prompt" class="style27"> </label></br>
  
	<?php 
for ($i=1;$i<=3;$i++){
?>
    
    <input type="text" name="textfield<?php echo $i; ?>" id="textfield<?php echo $i; ?>" onkeyup="validate()"/>
    </br>
  <?php  } ?>
  </p>
  </p>
  </span>
  <p>
  
    <input type="submit" name="button" id="button" value="Submit" onclick="checkVal()"/>
    <input type="reset" name="button2" id="button2" value="Reset" />
  </p>
</form>
</body>
</html>

Open in new window

0
 
786aslamkhanAuthor Commented:
@julainH:
Although very close to what exactly I was trying to achieve, this solution is probably even better than my goal. It was an exceptional experience and opportunity to learn from you, a true master and genius!

Thank you very much!

I will, however, try and use all that I have learnt from you through this question in trying to achieve what I originally set out for!

Thank you for your time, advice and code julianH!
0
 
Julian HansenCommented:
You are most welcome - thanks for the points and good luck.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.