表单在php中验证之前提交

表单在php中验证之前提交

问题描述:

I have a form which I want to submit, so when I click on submit it goes to the selectorpage.php and finds the selected function type e.g. login in this, which further calls the controller to execute the function. Issue I have is that there is a function called validateForm() in js, as soon as I click the submit button, it goes to the selectorPage.php. I wanted to stop the form submission, perform validation through js and then submit the form from there, I used onsubmit = return false; in form tag but it just blocks the form of doing anything further. And I also don't know how to redirect the form to the selectorPage if it somehow works in js. So anybody would like to give me an idea how to submit form from js and then redirect that page to selectorPage.php. Thanks

<form method="post" action="selector.php?type=login" id="login" id="loginForm">
      <div class="row">
           <div class="offset1 span1">            
                <div class="lbel">
                     <label class="control-label" for "loginName">
                          Username/Email
                     </label>
                </div>
                <div class="lbl_inpuCnt">
                      <input type="text" class="input-xlarge" id="loginName"
                             name="loginName" maxlength="50"/>
                </div>
                <div id="usernameError">&nbsp;</div>
                <div class="lbel">
                      <label class="control-label" for="loginPassword">
                             Password
                      </label>
                </div>
                <div class="controls">
                       <input type="password" class="input-xlarge" 
                               id="loginPassword" name="loginPassword" 
                                maxlength="50"/>
                </div>
                <div id="passwordError">&nbsp;</div><br/>
            </div>
       </div>
       <div style="margin-left: 55px;">
           <input class="btn" style="width: 80px;" type="reset" 
                    name="reset" value="Reset"/>
           <input class="btn" style="width: 80px;" type="submit" 
                    name="submit" value="Login" onclick="validateForm();"/>
       </div>
 </form>

this is the javascript according to the code above

function validateForm(){
    form = document.forms['loginForm'];
    if(document.getElementById('loginName').value == "")
        document.getElementById('usernameError').innerHTML = 'Invalid username or email';
    else{
        document.getElementById('usernameError').innerHTML = "&nbsp";      
    form.submit();
    }
} //suppose it for the email validation only for the time being

Here is the canonical way using inline event handling - see further down how it could be made unobtrusive. Also only have ONE id on the form tag, also NEVER call anything submit in a form it is a reserved word and will block submitting by script (which is what you tried to do)

<form id="loginform" ... onsubmit="return validate(this)">

<div style="margin-left: 55px;">
  <input class="btn" style="width: 80px;" type="reset" name="reset" value="Reset" onclick="clearFields()"/>
  <input class="btn" style="width: 80px;" type="submit"  value="Login" />
</div>
</form>

this is the javascript

function validateForm(form){ // passing form object
  document.getElementById('usernameError').innerHTML = ""; // reset

  if (form.loginName.value == "") {
    document.getElementById('usernameError').innerHTML = "Invalid username";
    return false;
  }
  return true;// allow submission
}

Alternative

<form id="loginform" ..... No event handler here ...>

Script:

window.onload=function() {
  document.getElementById("loginform").onsubmit=function() {
    document.getElementById('usernameError').innerHTML = ""; // reset

    if (this.loginName.value == "") { // notice the "this"
      document.getElementById('usernameError').innerHTML = "Invalid username";
      return false;
    }
    return true;// allow submission
  }
}

you could try

<form ... onsubmit="return validateForm();"

in the validateForm() function use

return true / false

depending if errors are found.

I've had similar issues to this in the past myself.

When you click the 'Login' button of your form, you are triggering two separate events - Calling of the 'validateForm();' javascript function, and submission of the form itself. The problem here, is that submitting the form involves the browser sending an outbound request back to the form target, and to my knowledge, there is no way, using javascript, to kill a request event once it has been triggered.

Using 'onsubmit=return false;', likely, is doing exactly what it is supposed to do - Exiting the current javascript scope (and therefore preventing further javascript associated to that particular event from executing). However, unfortunately, the submission of the form itself, while possible to trigger and control via javascript, is not actually handled by javascript and is not a javascript function itself.

What I've found, in my experiences, to be the best solution, is to use the 'button' type input instead of the 'submit' type input - Both 'submit' and 'button' appear as buttons, but 'button' doesn't actually have any default inherent associated event action (therefore, doesn't actually do anything when you click on it) - What this means, is that, via event handlers (such as 'onclick', as you've done), you are able to entirely control what happens when a user clicks on a 'button'.

You haven't included your 'validateForm();' javascript function here, so I don't know what it contains, but, if it doesn't already do so, I'd include code to submit the form via that javascript function, submitting the form once validation has been successful (or returning some sort of human readable error if validation fails) - That combined with using 'button' instead of 'submit' should solve your problem.

Hope this helps. :)

Edit: Thought of this shortly after making my initial reply. Some browsers will process events handlers such as 'onclick' prior to submitting forms via the submit input type; However, I've found that certain older browsers do not do this currently (thus context of my above post). For newer browsers that honour the results of event handlers processed prior to form submission, it should be possible to prevent the second event (form submission) from occurring at all if validation fails; However, not all browsers honour these results, and I've found that some will continue to submit the form regardless of those results.

well thanks u all, so finally I found the solution by your ideas here is what I have done rather putting return formvalidate(); function I put it in submit onclick event and it run like charm... thanks

<div style="margin-left: 55px;">
                    <input class="btn" style="width: 80px;" type="reset" name="reset" value="Reset" onclick="clearFields()"/>
                    <input class="btn" style="width: 80px;" type="submit" name="submit" value="Login" onclick="return validateForm();"/>
                </div>

this is the javascript

function validateForm(){
    var form = document.forms['loginForm'];
    if(document.getElementById('loginName').value == "")
        document.getElementById('usernameError').innerHTML = 'Invalid username or email';
    else{
        form.submit();
    }
    return false;
}