简体   繁体   中英

Validate form before submitting to php

Hello I'm implementing a login page everything is working fine from the PHP side but now I would implement one more function using jQuery: I would like to check if the fields of the login are empty and if not than print something on the page, otherwise continue with php, how to do that?

Here is part of my HTML code:

<form id="loginForm" action="login-exec.php" name="loginForm" method="post" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
    <fieldset>
        <div data-role="fieldcontain">
            <label class="ui-input-text" for="login">Login:</label>
            <input name="login" type="text" class="textfield" id="login" />
        </div>                                  
        <div data-role="fieldcontain">                                      
            <label class="ui-input-text" for="password">Password:</label>
            <input name="password" type="password" class="textfield" id="password"/> 
        </div>
        <input type="submit" name="Submit" value="Login" />
    </fieldset>
</form>     

Bind an event to the submission of the form (Note: NOT the click of a submit button). That's where your code goes that checks the form, and if necessary, stops it from being posted.

$('#loginForm').on('submit', function(e){
    if ($('#login').val()=='' || $('#password').val()==''){
        e.preventDefault();
        // alert('Fill in both fields');
        // You can use an alert or a dialog, but I'd go for a message on the page
        $('#errormsg').text('Fill in both fields').show();
    }else{
        // do nothing and let the form post
    }
});

If you prefer to show a message than use a dialog, somewhere on the page, preferably near the Submit button add the errormsg div

<p id="errormsg" style="display:none;"></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM