How to validate a hidden field?

I’m trying to figure out how to validate a hidden field on my form. The value for the hidden field is added when the user submits a second form via a popup. So the value of the hidden field is coming from a different form and is added dynamically with javascript.

Here is the html of the hidden field

<div class="form-group">
  <label  class="" for="fname"></label>   
  <input type="hidden" name="customerVehicles" class="customerVehicles form-control"   
 id="customerVehicles"   />   
</div><!-- close form group -->  

Here is the javascript that populates the hidden field

    $('#add').click(function(){
          
      // store field values
      var vehmodel = $("#model").val();
      var vehmake = $("#make").val();
      var vehyear = $("#year").val();
      var primaryUse = $("#primaryUse").val();
      var ownership = $("#ownership").val();

      if(vehmodel && vehmake && vehyear && primaryUse && ownership){
         
              // concatinate variables to one variable
              var vehP = vehyear+" : "+vehmake+" : "+vehmodel+" : "+ownership+" : "+primaryUse;
              
              // add value to hidden field
              $('#customerVehicles').attr('value', vehP);

      }// end if
      else{
        alert ("Please add at least one vehicle.");
      }
    });// close .click

Here is the validation script that I want to check that there is a hidden field value

    $('#step2').bootstrapValidator({
       message: 'This value is not valid',
       live: 'enabled',
       feedbackIcons: {
       valid: 'glyphicon glyphicon-ok',
       invalid: 'glyphicon glyphicon-remove',
       validating: 'glyphicon glyphicon-refresh'
      },
      submitHandler: function(validator, form, submitButton) {
          ...
      },
      excluded: ':disabled',
      fields: {

          customerVehicles: {
              message: 'Please Make a Selection',
              validators: {
              notEmpty: {
                  message: 'Please Make a Selection'
              }    
            }
          }// end dropdown

       } // end field
    });// bootstrapValidator

I’m on my iPad right now, so sorry for the short relpy.
Anyway, this link should help: http://bootstrapvalidator.com/examples/adding-dynamic-field/

The problem is occuring as the field is being added dynamically.

1 Like

if the validation of the hidden field fails, how is the user supposed to know how to fix it?

1 Like

good point Dormilich. I guess I don’t have anything that appears for that field when the invalid form fires. I do have a p tag that says “no vehicle selected” which is hidden once they select a vehicle. I pulled that out of the code that it displayed for simplicity.

Pullo, i checked out that link, but I’m not sure if that is what i’m doing. It seems those examples are adding a new cloned field. So if the user doesn’t add a new field there is nothing to validate. In my case, the hidden field is always there. Does that make sense?

Here is a link to the site to put it in context:

Oh ok.

So, is the value of the hidden field set once the user has added a vehicle?

yes. it’s added in the #add.click function.

What value are you expecting it to contain when a vehicle has been added?

example: 2012 Audi A5 - Commute - Financed

right now i have it concatenating all the values from the popup to create one string for that vehicle, but I don’t really need to do it that way now because I’m storing that info in a db each time they add a vehicle. So it could be a boolean if that it easier.

Ah ok. The hidden field wasn’t being populated for me before.
Now it is. All good.

It seems that by default, the hidden, invisible fields will not be validated.

Try setting the excluded option:

excluded: ':disabled, :hidden, :not(:visible)',

Does that help any?

yep! Thanks again pullo!

No problem.
You might not need :not(:visible), so see if things still work if you remove it.

Don’t validate the hidden field - instead add the validation to the process that is adding the value into the hidden field.

For people with JavaScript off the hidden field will still be empty when the form is submitted so another alternative is to simply omit the hidden field and generate the value on the server after the form is submitted.

The section where you can add a vehicle doesn’t work at all for people with JS disabled, so the form seems quite unusable without JavaScript.

Whether the time and effort involved in fixing this will outweigh the benefit is a different question.
I’m so used to forms (especially) needing JS to work nowadays, I would simply enable JavaScript on this page.

Saying that, I still think that progressive enhancement is still the way to go, and if one considers this when designing the site, it isn’t particularly hard to implement.

In which case since the hidden field can only be set when that other section is filled in you don’t need to validate the hidden field since if the values filled in those other fields are valid then the hidden field must be valid and if the other fields are not filled in then they are not valid.

The validation isn’t working as expected. Currently it is triggering the validation error when the hidden field is blank, but after it triggers it won’t validate even after the user then adds a vehicle. It does work if the user selects a vehicle before attempting to submit the form. Any ideas?

As for the js issue, at some point I’ll redesign the forms at which time I would consider employing a more “progressive enhancement” approach, but for now I’m relying on the user having js enabled. My reasoning is that less than 2% have their js disabled, and with our audience it’s probably much lower (although i should test this now that we are talking about it).

What I would do now, if this were me, is to make a bare bones example which demonstrates the problem you are having and only that problem.

If you can post something along those lines, maybe folks can help more.

Ok i pulled almost everything out and created a much simpler page with just 2 form fields, and the vehicle form.

Here is the new script

<script type="text/javascript">
    $(document).ready(function() {
        
        $('#step2').bootstrapValidator({
            message: 'This value is not valid',
            excluded: ':disabled, :hidden',
            live: 'enabled',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            submitHandler: function(validator, form, submitButton) {
       
                alert("Successful Form Submit");
                
            },
            excluded: ':disabled',
            fields: {
                coverage: {
                    validators: {
                        notEmpty: {
                            message: 'Please select level of coverage'
                        }
                    }
                },
                 creditRating: {
                     message: 'Please Make a Selection',
                     validators: {
                        notEmpty: {
                            message: 'Please Make a Selection'
                        }    
                    }
                 },// end dropdown
                 customerVehicles: {
                     message: 'Please add a vehicle',
                     validators: {
                        notEmpty: {
                            message: 'Please add a vehicle'
                        }    
                    }
                 }// end dropdown
            } // end field
        });// bootstrapValidator

       $('#add').click(function(){
              
          // store field value 
          var vehyear = $("#year").val();
          if(vehyear){   
            
            //flag for hidden field
            var veh = "vehicle added";
            // add value to hidden field
            $('#customerVehicles').attr('value', veh);

          }// end if
          else{
            alert ("Please add at least one vehicle.");
          }
        });// close .click

    }); //ready(function
    </script>

Here is a link to it
http://aaronhaas.com/bsi25/form-auto-t.php

Hi,

Nice one!
So how can we reproduce the problem you are having?

Sorry I got pulled away mid post…

So it validates if you run through the form and select everything. But if you select the first two items and hit submit the forms locks up and won’t allow another submit.

Hi,

So this is the thing with these validator plugins. They’re great when they work, but you end up fighting them tooth and nail when they don’t.

Here’s one way to do it:

<!DOCTYPE html>
<html lang="en">
  <head>
  <base href="http://aaronhaas.com/bsi25/"/>
    <meta charset="utf-8">
    <title>Best Selling Insurance</title>

    <!-- Bootstrap core CSS -->
    <link rel="stylesheet" href="assets/css/bootstrap.min.css" >
    <link rel="stylesheet" href="assets/css/font-awesome.min.css">
    <link rel="stylesheet" href="assets/css/bootstrapValidator.css"/>
    <link href="assets/css/bsi2.css" rel="stylesheet">
    <link href="assets/css/form.css" rel="stylesheet">

    <!--   jquery -->
    <script src="assets/jquery/jquery-1.11.1.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="assets/js/bootstrapValidator.min.js"></script>
  </head>

  <body>
      <div class="container">
        <div class="row">
          <form id="registrationForm" method="post" class="form-horizontal" action=".">
            <div class="form-group">
              <label class="col-lg-3 control-label">Username</label>
              <div class="col-lg-5">
                <input type="text" class="form-control" name="username" />
              </div>
            </div>

            <div class="form-group">
              <label class="col-lg-3 control-label">Email address</label>
              <div class="col-lg-5">
                <input type="text" class="form-control" name="email" />
              </div>
            </div>

            <div class="form-group">
              <label class="col-lg-3 control-label">Your Vehicles</label>
              <div class="col-lg-5">
                <div class="table-responsive">
                  <table class="table" id="selected-vehicles">
                  </table>
                </div>
                <a href="#" class="btn btn-success" data-toggle="modal" data-target="#basicModal">Click to add vehicle</a>
              </div>
            </div>

            <!-- vehicle modal -->
            <div class="modal fade" id="basicModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
              <div class="modal-dialog">
                <div class="modal-content">
                  <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">Add vehicle</h4>
                  </div>
                  <div class="modal-body">
                    <h3>Choose your model</h3>
                     <div class="form-group">
                      <select class="form-control" name="vehicles">
                        <option value=''>Please select</option>
                        <option value="porsche">Porsche</option>
                        <option value="bmw">BMW</option>
                        <option value="lotus">Lotus</option>
                      </select>
                    </div>
                  </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="addVehicle">Add</button>
                  </div>
                </div>
              </div>
            </div>
            <div class="form-group">
              <div class="col-lg-9 col-lg-offset-3">
                <button type="submit" class="btn btn-default">Sign up</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>

    <script>
    $('#myModal').modal();

      $('#registrationForm').bootstrapValidator({
        feedbackIcons: {
          valid: 'glyphicon glyphicon-ok',
          invalid: 'glyphicon glyphicon-remove',
          validating: 'glyphicon glyphicon-refresh'
        },
        submitHandler: function(validator, form, submitButton) {
          // Custom  validations here
          if ($("#selected-vehicles tr").length === 0){
            alert("Please select a vehicle");
            $("button[type='submit']").removeAttr('disabled');
            return false;
          }
        },
        fields: {
          username: {
            message: 'The username is not valid',
            validators: {
              notEmpty: {
                message: 'The username is required and cannot be empty'
              },
            }
          },
          email: {
            validators: {
              notEmpty: {
                message: 'The email address is required and cannot be empty'
              },
            }
          },
          vehicles: {
            validators: {
              notEmpty: {
                message: 'The vehicle make is required and cannot be empty'
              },
            }
          }

        }
      });

      $("#addVehicle").on("click", function(){
        var bootstrapValidator = $("#registrationForm").data('bootstrapValidator');
        if(!bootstrapValidator.validateField('vehicles').$invalidFields.length){
          $("#selected-vehicles").append("<tr><td>" + $("select[name='vehicles']").val() +"</td></tr>");
          $('.modal.in').modal('hide');
        }
      });
    </script>
  </body>
</html>

As you can see I have made the modal part of the form, which helps with the validation.

Maybe (probably) there is a better way to do this, but this should get you started.

Demo.

HTH