简体   繁体   中英

How to perform on-submit form validation

I want to replace the after-submission checks in the form with on-the-fly completeness and correctness checks that are performed when a form field loses focus.

How can I do this?

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE HTML> <html> <head> <title>Form</title> <style> body { width: 500px; } .part { width: 100%; padding: 5px; border-bottom: 1px solid #000; } label { margin-right: 5px; } .label-left { text-align: right; } .label-right { text-align: left; } .error { color: #cc0000; } </style> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script> //$(document).ready(function() { function myValidateEMailAddress(email_address) { var email_pattern = /^([\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4})?$/; return email_pattern.test(email_address); } function checkPassword(pwd_str) { var my_pwd_pattern = /^(?=.*[a-zA-Z].*[a-zA-Z])(?=.*\\d.*\\d)[a-zA-Z0-9_]{6,20}$/; return my_pwd_pattern.test(pwd_str); } function validatePhoneNumber(phone_number) { var phone_pattern = /^(\\(?\\+?[0-9]*\\)?)?[0-9_\\- \\(\\)]*$/; return phone_pattern.test(phone_number); } $(document).ready(function() { $('#form').submit(function(e) { var my_errors = false; $('.part> .error').remove(); $('#my_submission').empty(); $(':text, :password, textarea').each(function() { $(this).val($.trim($(this).val())); if ($(this).val() == '') { $(this).parent().append('<div class="error">Please provide a value</div>'); my_errors = true; } }); if ($('#email').val() != '') { if (!myValidateEMailAddress($('#email').val())) { $('#email').parent().append('<div class="error">Please provide a correct e-mail address</div>'); my_errors = true; } } if ($('#your_password').val() != '') { if (!checkPassword($('#your_password').val())) { $('#your_password').parent().append('<div class="error">Please provide a correct password.</div>'); my_errors = true; } } if ($('#phone').val() != '') { if (!validatePhoneNumber($('#phone').val())) { $('#phone').parent().append('<div class="error">Please provide a correct phone number.</div>'); my_errors = true; } } if ($('#addresses option:selected').val() == '') { $('#addresses').parent().append('<div class="error">Please select one item</div>'); my_errors = true; } if ($(':radio[name="sex"]:checked').length == 0) { $(':radio[name="sex"]:first').parent().after('<div class="error">Please select one item</div>'); my_errors = true; } if ($(':radio[name="subscription"]:checked').length == 0) { $(':radio[name="subscription"]:first').parent().after('<div class="error">Please select one item</div>'); my_errors = true; } if ($('#likes option:selected').val() == '') { $('#likes').parent().append('<div class="error">Please select one item</div>'); my_errors = true; } if (my_errors) { return false; } else { e.preventDefault(); var my_submission_array = $('#form').serialize().split('&'); if (my_submission_array.length > 0) { $('#my_submission').html('<h2>Submitted Elements</h2><ul></ul>'); for (var i = 0; i < my_submission_array.length; i++) { var my_pair = my_submission_array[i].split('='); $('#my_submission > ul').append('<li>' + my_pair[0] + ': ' + my_pair[1] + '</li>\\n'); } } } }); }); // }); </script> </head> <body> <h3>Output:</h3> <h2>My Questionnaire</h2> <form name="form" id="form" action="" method="post"> <div class="part"> <label for="addresses" class="label-left">How should you be addressed?</label> <select name="addresses" id="addresses"> <option value="">Please select one</option> <option value="first">Mr.</option> <option value="second">Madam</option> <option value="third">Miss</option> <option value="fourth">Dr.</option> <option value="fifth">Pr.</option> </select> </div> <div class="part"> <fieldset> <legend>Sex:</legend> <input type="radio" name="sex" id="group1" value="1"> <label for="group1" class="label-right">Male</label> <input type="radio" name="sex" id="group2" value="2"> <label for="group2" class="label-right">Female</label> </fieldset> </div> <div class="part"> <label for="last_name" class="label-left">Last Name: </label> <input type="text" name="last_name" id="last_name"> </div> <div class="part"> <label for="first_name" class="label-left">First Name: </label> <input type="text" name="first_name" id="first_name"> </div> <div class="part"> <label for="email" class="label-left">E-Mail: </label> <input type="text" name="email" id="email"> </div> <div class="part"> <label for="your_password">Password:</label> <input type="password" name="your_password" id="your_password" size="10" maxlength="20"> </div> <div class="part"> <label for="phone" class="label-left">Phone number: </label> <input type="text" name="phone" id="phone"> </div> <div class="part"> <label for="likes" class="label-left">What are your likes?</label> <select name="likes" id="likes"> <option value="">Please select one</option> <option value="first">Programming</option> <option value="second"> African literature</option> <option value="third">Poetry</option> <option value="four">Dancing</option> </select> </div> <div class="part"> <fieldset> <legend>Do you want to receive our newsletter ?</legend> <input type="radio" name="subscription" id="group1" value="1"> <label for="group1" class="label-right">Yes</label> <input type="radio" name="letter" id="group2" value="2"> <label for="group2" class="label-right">No</label> </fieldset> </div> <div class="part"> <label for="comments" class="label-left">Write some comments below:</label> <textarea name="comments" id="comments" cols="40" rows="3"></textarea> </div> <div class="part"> <input type="submit" name="submit" id="submit" value="Submit Form"> </div> <div id="my_submission"></div> </form> </body> </html> 

Before I continue answering, I should note that you're putting jQuery script before <html> tag. This is incorrect. It has to be in <head>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
...

performed when a form field loses focus

An element loses focus when you click away from it. jQuery happends to have a blur event for this occasion:

$('input').on('blur', function() {
    // your code here
});

So you might want to do it this way:

$('#email').on('blur', function() {
    var emailVal = $(this).val();
    if (!emailVal || !myValidateEMailAddress(emailVal)) {
        $(this).parent().append('<div class="error">Please provide a correct e-mail address</div>');
        my_errors = true;
    }
});

the rest of the code might look similar.

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