jQuery Mobile Form Validation

10,390

Solution 1

For a small form like that, I wouldn't bother using a plugin - is it even compatible with jQuery Mobile? Anyway, to get you started, here's a simple way to prevent submission when there are empty fields:

$("#formL").submit(function() {

    // get a collection of all empty fields
    var emptyFields = $(":input.required").filter(function() {

        // $.trim to prevent whitespace-only values being counted as 'filled'
        return !$.trim(this.value).length;
    });

    // if there are one or more empty fields
    if(emptyFields.length) {

        // do stuff; return false prevents submission
        emptyFields.css("border", "1px solid red");   
        alert("You must fill all fields!");
        return false;
    }
});

You can try it/mess with it here.

Solution 2

I have ran across the same problem you have, I have my form validating correctly now.

The following is what I have done with Jquery Mobile -->

<link rel="stylesheet" href="css/jquery.mobile-1.0a4.1.css" />
<link rel="stylesheet" href="css/colors.css">
<link rel="stylesheet" href="css/list.css">
<!--For Icon to bookmark on phones-->
<link rel="apple-touch-icon-precomposed" href=""/>
<script>     

var hdrMainvar = null;
var contentMainVar = null;
var ftrMainVar = null;
var contentTransitionVar = null;
var stateLabelVar = null;
var whatLabelVar = null;
var stateVar = null;
var whatVar = null;
var form1var = null;
var confirmationVar = null;
var contentDialogVar = null;
var hdrConfirmationVar = null; 
var contentConfirmationVar = null;
var ftrConfirmationVar = null;
var inputMapVar = null;

// Constants
var MISSING = "missing";
var EMPTY = "";
var NO_STATE = "ZZ";
</script>

<div data-role="header" id="hdrMain" name="hdrMain" data-nobackbtn="true">

</div>

<div  data-role="content" id="logo" align="center">
<img src="img/sam_mobile.png">
</div>

<div data-role="content" id="contentMain" name="contentMain">   

<form id="form1">

<div id="userDiv" data-role="fieldcontain">
    <label for="userName">User Name*</label>        
    <input id="userName" name="userName_r" type="text" />
</div>

<div id="passwordDiv" data-role="fieldcontain">
    <label for="password" id="passwordLabel" name="passwordLabel">Password*</label>     
    <input id="password" name="password_r" type="password" />
</div>

<div id="submitDiv" data-role="fieldcontain">    
 <input type="submit" value="Login" data-inline="true"/>
</div>
</form>
</div><!-- contentMain -->

<div data-role="footer" id="ftrMain" name="ftrMain"></div>

<div align="CENTER" data-role="content" id="contentDialog" name="contentDialog">    

    <div>You must fill in both a user name and password to be granted access.</div>
         <a id="buttonOK" name="buttonOK" href="#page1" data-role="button" data-inline="true">OK</a>
</div>  <!-- contentDialog -->

         <!-- contentTransition is displayed after the form is submitted until a response is received back. -->
<div data-role="content" id="contentTransition" name="contentTransition">   
    <div align="CENTER"><h4>Login information has been sent. Please wait.</h4></div>
    <div align="CENTER"><img id="spin" name="spin" src="img/wait.gif"/></div>
</div>  <!-- contentTransition -->

<div data-role="footer" id="ftrConfirmation" name="ftrConfirmation"></div> 


<script>

$(document).ready(function() {
//Assign global variables from top of page
  hdrMainVar = $('#hdrMain');
  contentMainVar = $('#contentMain');
  ftrMainVar = $('#ftrMain');
  contentTransitionVar = $('#contentTransition');
  stateLabelVar = $('#stateLabel');
  whatLabelVar = $('#whatLabel');
  stateVar = $('#state');
  whatVar = $('#what');
  form1Var = $('#form1');
  confirmationVar = $('#confirmation');
  contentDialogVar = $('#contentDialog');
  hdrConfirmationVar = $('#hdrConfirmation');
  contentConfirmationVar = $('#contentConfirmation');
  ftrConfirmationVar = $('#ftrConfirmation'); 
  inputMapVar = $('input[name*="_r"]');

  hideContentDialog();
  hideContentTransition();
  hideConfirmation();



}); 

  $('#buttonOK').click(function() {
  hideContentDialog();
  showMain();
  return false;      
});


$('#form1').submit(function() {
    //Start with false to hide specific div tags
    var err = false;
    // Hide the Main content
    hideMain();

    // Reset the previously highlighted form elements
    stateLabelVar.removeClass(MISSING); 
    whatLabelVar.removeClass(MISSING);              
    inputMapVar.each(function(index){              
      $(this).prev().removeClass(MISSING); 
    });

    // Perform form validation
    inputMapVar.each(function(index){  
    if($(this).val()==null || $(this).val()==EMPTY){  
        $(this).prev().addClass(MISSING);            
        err = true;
      }          
    });   
    if(stateVar.val()==NO_STATE){           
      stateLabelVar.addClass(MISSING);                     
      err = true;
    }                    
    // If validation fails, show Dialog content
    if(err == true){            
      showContentDialog();
      return false;
    }        

    // If validation passes, show Transition content
    showContentTransition();

    // Submit the form
    $.post("requestProcessor.php", form1Var.serialize(), function(data){
        //DB Validation goes here when we link to the Db
      confirmationVar.text(data);
      hideContentTransition();
      window.location="access.php";
    });        
    return false;      
});    



 function hideMain(){
    hdrMainVar.hide();
    contentMainVar.hide();
    ftrMainVar.hide();   
   }

  function showMain(){
    hdrMainVar.show();
    contentMainVar.show();
    ftrMainVar.show();
   }

   function hideContentTransition(){
    contentTransitionVar.hide();
   }      

   function showContentTransition(){
    contentTransitionVar.show();
   }  

  function hideContentDialog(){
    contentDialogVar.hide();
   }   

   function showContentDialog(){
    contentDialogVar.show();
   }

   function hideConfirmation(){
    hdrConfirmationVar.hide();
    contentConfirmationVar.hide();
    ftrConfirmationVar.hide();
   }  

   function showConfirmation(){
    hdrConfirmationVar.show();
    contentConfirmationVar.show();
    ftrConfirmationVar.show();
   } 


  </script>

This will not allow the form to be submitted if there is empty fields. Feel free to take this code and manipulate and play with it as much as you like. As you can see I used a .php file, just like you, to handle the validation of the user.

Share:
10,390
Seven
Author by

Seven

Updated on June 04, 2022

Comments

  • Seven
    Seven almost 2 years

    I have a mobile website and everything is working fine except for the validation. Basically I'm looking to take values from the user and then process them on a separate page (process.php). However, before doing so I need to check to make sure the fields have been populated. I have looked at several ways to do this but none seem to be working. I have the below code at the moment. When I press the process button it brings me through to the process.php splash screen even though the item field is empty. It doesn't write to the database but I would rather it didn't bring the user to the process.php screen until all mandatory fields have been filled in. Any ideas?

    <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
    
    <script>
      $(document).ready(function(){
      $("#formL").validate(); });
    </script>
    
    
    
    <div data-role="content">
    
          <form id="formL" action="/website/process.php" method="post">
          <div data-role="fieldcontain">
            <label for="item">
            <em>* </em> <b>Item:</b> </label>
            <input type="text" id="item" name="item" class="required" />
          </div>
    
          <div class="ui-body ui-body-b">
            <button class="buttonL" type="submit" data-theme="a">Process</button>
          </div>
        </form>
    
    </div>
    
  • Seven
    Seven about 13 years
    Thanks for the response. Can't seem to get the above to work. Where should I place this code? I have one index.php file that contains internal links to #first (page), #second and #third. The form I'm looking to validate is on #third. This then externally links to process.php which writes the values to the database. Thanks.
  • Omar
    Omar about 11 years
    +1 Easy and clean! much better than jquery.validate.js, since it doesn't work with data-role="dialog"