0

I need some help with JavaScript for Form validation using for inside the JavaScript.

I have a form that contains 5 fields for username and password and need to use JavaScript for validation of the form before it can be submitted to database.

You can see the code and the result that I need here in this JsFiddle

or

This is the code from my view :

<form action="insertMember" method="post" name="fmember" onsubmit="return validateMember()">
    <div class="form-group">
       <label>Shop</label>
       <select>
          <option value="">Choose The Host</option>
          <option value="1">Shop 1</option>
          <option value="2">Shop 2</option>
       </select>
    </div>
    <?php 
    $max = 5;
    for($i=1; $i<=$max; $i++) { ?>
       <span class="error<?php echo $i; ?>" class="label label-danger"></span>
       <label>Username <?php echo $i; ?></label>
       <input type="text" name="user[<?php echo $i; ?>]">
       <label>Password <?php echo $i; ?></label>
       <input type="password" name="pass[<?php pass $i; ?>]">
       <span class="errorp<?php echo $i; ?>" class="label label-danger"></span>
    <?php } ?>
</form>

This is the code from my Javascript (still error) :

// How to validate input using FOR LOOP ?
// $max or max can be changes to 10 or more.
function validateMember() {
// I got an error from here.
        var max = 3;
    var member = [];
    var password = [];
    for(var i=1; i<=max; i++) {
        var member = document.forms.fmember.user[i].value;
        var password = document.forms.fmember.pass[i].value;
      // Validate only username 1 must be filled or return error message
      if(i == 1) {
         if(member[i] == '') {
             document.getElementByID('error'+i).innerHTML = 'Username Must be Filled !';
             return !1;
         }
         else if (password[i] == '') {
                 document.getElementByID('errorp'+i).innerHTML = 'Password Must be Filled !';
             return !1;
         }
         else {
             return !0;
         }
      }
      else {
      // Validate if username 2 until MAX are filled must have min length = 2
         if(member[i] != '') {
               if(member[i].length < 2) {
                         document.getElementByID('error'+i).innerHTML = 'Username Must Have Minimum 2 Characters';
                       return !1;
                 }
             else {
                            return !0;
                }
         }
      }
    }
}

2 Answers 2

1

There are multiple issues here:

  1. The name attribute values of the input elements have the array syntax

    <input type="text" name="user[1]">
    

    But when accessing those via Javascript, document.forms.fmember does not contain an array at key user - each element has a unique key. Try running this in your console: Object.keys(document.forms.fmember.elements). You should see an array like below:

    ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "shop", "user[1]", "pass[1]", "user[2]", "pass[2]", "user[3]", "pass[3]", "user[4]", "pass[4]", "user[5]", "pass[5]"]
    

    So update this line:

     var member = document.forms.fmember.user[i].value;
    

    To:

     var member = document.forms.fmember["user["+i+"]"].value;
    

    And the same for the password variable:

    var password = document.forms.fmember["pass["+i+"]"].value;
    
  2. Those variables that contain the text input values (i.e. member and password) have a value that is of type string, so to check for an empty string, just use if(member == '') { instead of if(member[i] == '') {...

See these changes in action below (or an updated plunker).

$('#shop').on('change',function() {
		$('#input').fadeIn(1000);
		if ($('#shop').val() == '') {
    		$('#input').fadeOut(500);
     }
});

// The question is HERE
// How to validate input using FOR LOOP ?
// Because the $max or max can be changed to 10 or more.
function validateMember() {
// I got an error from here.
		var max = 3;
    var member = [];
    var password = [];
    for(i=1; i<=max; i++) {
    		var member = document.forms.fmember["user["+i+"]"].value;
        var password = document.forms.fmember["pass["+i+"]"].value;
      // Validate only username 1 must be filled or return error message
      if(i == 1) {
         if(member== '') {
      	     document.getElementById('error'+i).innerHTML = 'Username Must be Filled !';
      	     return !1;
         }
         else if (password == '') {
      			 document.getElementById('errorp'+i).innerHTML = 'Password Must be Filled !';
          	 return !1;
         }
         else {
             return !0;
         }
      }
      else {
      // Validate if username 2 until MAX are filled must have min length = 2
         if(member != '') {
      		   if(member.length < 2) {
       				 	 document.getElementByID('error'+i).innerHTML = 'Username Must Have Minimum 2 Characters';
      				   return !1;
        		 }
             else {
      						return !0;
      			}
         }
      }
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<!-- This code is not the actually code, this code is just for an example -->
<div id="#formMember">
  <h3>Input Member</h3>
    <form name="fmember" onsubmit="return validateMember()">
      <div>
         <label>shop</label>
         <select id="shop">
             <option value="">Choose The Shop..</option>              
             <option value="1">Shop 1</option>            
             <option value="2">Shop 2</option>
         </select>
      </div>
      <hr />
      <div id="input">
      <!-- This is actually use PHP for loop, i dont know how to use it at JsFiddle
      <?php 
      $max = 3; //so sometimes we can change it if want to add more fields.
      for($i=1; $i<$max; $i++) { ?>
        <div class="form-group">
          <span class="error<?php echo $i; ?>" class="label label-danger"></span>
          <label>Username <?php echo $i; ?></label>
          <input type="text" name="user[<?php echo $i; ?>]">
          <label>Password <?php echo $i; ?></label>
          <input type="password" name="pass[<?php pass $i; ?>]">
          <span class="errorp<?php echo $i; ?>" class="label label-danger"></span>
        </div>
     <?php } ?>
      -->
      <h4>This is just an example after this form submitted</h4>
          <div class="form-group">
              <span id="error1" class="label label-danger">Username 1 Must be Filled !<br></span>
              <label>Username 1</label>
              <input type="text" name="user[1]">
              <label>Password 1</label>
              <input type="password" name="pass[1]">
              <span id="errorp1" class="label label-danger">Password 1 Must Be Filled !<br></span>
          </div>
          <div class="form-group">
              <span id="error2" class="label label-danger">Username 2 Must Have Minimum 2 Characters !<br></span>
              <label>Username 2</label>
              <input type="text" name="user[2]" value="a">
              <label>Password 2</label>
              <input type="password" name="pass[2]" value="xxxxx">
              <span id="errorp2" class="label label-danger"></span>
          </div>
          <div class="form-group">
              <span id="error3" class="label label-danger"></span>
              <label>Username 3</label>
              <input type="text" name="user[3]">
              <label>Password 3</label>
              <input type="password" name="pass[3]">
              <span id="errorp3" class="label label-danger"></span>
          </div>
          <div class="form-group">
              <span id="error4"></span>
              <label>Username 4</label>
              <input type="text" name="user[4]" value="username2">
              <label>Password 4</label>
              <input type="password" name="pass[4]">
              <span id="errorp4" class="label label-danger">Password 4 Must Be Filled !<br></span>
          </div>
          <div class="form-group">
              <span id="error5"></span>
              <label>Username 5</label>
              <input type="text" name="user[5]">
              <span id="errorp5"></span>
              <label>Password 5</label>
              <input type="password" name="pass[5]"> 
          </div>
          <button type="submit" class="col-sm-offset-2 btn btn-primary">
            Submit
          </button>
       </div>
    </form>
</div>

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much Sam, it's working very well now !
Hi sam, instead of creating variable max on JavaScript. Is there anyway to get user.length like input.length ? So, if sometimes the $max input on PHP file changes by Admin User its no need to change var max = 5 on JS file.
If the value would come from PHP you can render a <script> tag with that value in a JS variable... otherwise if it depends on how many inputs are filled in, it might be more complicated. Perhaps you should post a new question with the details of where that value comes from.
1

I am not sure what the code is trying to do with the max variable, however this should get you on your way:

$.each( $( "#input input" ), function( key, element ) {

        if( !$(element).val() ) {

            $( "#error" + key ).text( "Input " + $( element ).attr( "name" ) + " is required" );

            return false;

    }

});

Simply replace the old JS with this.

2 Comments

Sorry it's not working, am I wrong while put the code ?
Describe what isn't working and if there are any errors please.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.