2011-04-17 3 views
3

У меня есть мобильный сайт, и все работает нормально, за исключением проверки. В основном я ищу, чтобы принимать значения от пользователя, а затем обрабатывать их на отдельной странице (process.php). Однако, прежде чем делать это, мне нужно проверить, чтобы поля были заполнены. Я рассмотрел несколько способов сделать это, но никто, похоже, не работает. На данный момент у меня есть код ниже. Когда я нажимаю кнопку процесса, она приводит меня к всплывающему экрану process.php, хотя поле элемента пуст. Он не пишет в базу данных, но я предпочел бы, чтобы пользователь не перешел на экран process.php, пока все обязательные поля не были заполнены. Любые идеи?jQuery Mobile Form Validation

<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> 

ответ

6

Для небольшой формы, как это, я бы не стал заморачиваться с помощью плагина - это даже совместимо с JQuery Mobile? В любом случае, чтобы вы начали, вот простой способ предотвратить подачу, когда есть пустые поля:

$("#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.

+0

Спасибо за ответ. Кажется, вы не можете заставить выше работать. Где я должен разместить этот код? У меня есть один файл index.php, содержащий внутренние ссылки на #first (page), #second и #third. Форма, которую я ищу для проверки, находится на третьем месте. Затем он внешне ссылается на process.php, который записывает значения в базу данных. Благодарю. – Seven

+0

Спасибо, работает как шарм :) – Stiropor

+0

** + 1 ** Легко и чисто! намного лучше, чем jquery.validate.js, поскольку он не работает с диалогом 'data-role =" '' – Omar

1

я натыкался на одной и той же проблемы у вас есть, у меня есть форма правильно проверки в настоящее время.

Ниже то, что я сделал с 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> 

Это не будет в llow form, который будет отправлен, если есть пустые поля. Не стесняйтесь принимать этот код и манипулировать и играть с ним столько, сколько хотите. Как вы можете видеть, я использовал файл .php, как и вы, для обработки проверки пользователя.