Solved

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

Posted on 2014-02-25
10
325 Views
Last Modified: 2014-02-27
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
0
Comment
Question by:786aslamkhan
  • 5
  • 4
10 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39886265
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
 

Author Comment

by:786aslamkhan
ID: 39887997
@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
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39888089
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
 

Author Comment

by:786aslamkhan
ID: 39888176
@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
 
LVL 9

Expert Comment

by:Sar1973
ID: 39888229
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:786aslamkhan
ID: 39888369
@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
 

Author Comment

by:786aslamkhan
ID: 39891141
@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
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 39891270
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
 

Author Closing Comment

by:786aslamkhan
ID: 39891438
@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
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39891495
You are most welcome - thanks for the points and good luck.
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
This video teaches viewers how to create their own website using cPanel and Wordpress. Tutorial walks users through how to set up their own domain name from tools like Domain Registrar, Hosting Account, and Wordpress. More specifically, the order in…
Wufoo.com provides powerful tools for surveying targeted groups, and utilizing data from completed surveys to find trends, discover areas of demand or customer expectation, and make business decisions on products or services.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now