Submitting form after validating inputs

RoyNasr

I have the following registration form :

<form id="register-form" method="post" role="form" style="display: none;" 

action="">
    <div class="form-group">
        <input type="text" name="firstname" id="firstname" tabindex="1" class="form-control" placeholder="Firstname" value="" required>
        <span class="error" id="fnError"></span>
    </div>
    <div class="form-group">
        <input type="text" name="lastname" id="lastname" tabindex="1" class="form-control" placeholder="Lastname" value=""required>
        <span class="error" id="lnError"></span>
    </div>
    <div class="form-group">
        <input type="email" name="email2" id="email2" tabindex="1" class="form-control" placeholder="Email Address" value=""required>
    </div>
    <div class="form-group">
        <input type="password" name="password2" id="password2" tabindex="2" class="form-control" placeholder="Password"required>
        <span class="error" id="pass2Error"></span>
    </div>
    <div class="form-group">
        <input type="password" name="confirm_password" id="confirm-password" tabindex="2" class="form-control" placeholder="Confirm Password" required>
        <span class="error" id="confError"></span>
    </div>
    <div class="form-group">
        <div class="row">
            <div class="col-sm-6 col-sm-offset-3">
                <input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">
                <span class="throw_error" id="success"></span>
                <div id="divLoader"></div>
            </div>
            <div class="col-sm-6 col-sm-offset-3">
                <span id="result"></span>
            </div>
        </div>
    </div>
</form>

And I am using the jquery validation plugin to validate the inputs :

jQuery.validator.setDefaults({
        debug: false,
        success: "valid"
    });
    $('#register-form').validate({
        rules:{
            firstname :{
                required : true,
                minlength : 3,
                maxlength : 15
            },
            lastname :{
                required : true,
                minlength : 3,
                maxlength : 15
            },
            email2:{
                required : true,
                email : true
            },
            password2:{
                required : true,
                minlength : 8,
                maxlength : 15
            },
            confirm_password:{
                required : true,
                minlength : 8,
                maxlength : 15,
                equalTo : "#password2"
            }
        }
    });

When I click on the registration button, the validation of the fields is shown (all the errors on each field are shown), and the ajax code that I am using on the button press runs even if there are validation errors. Here is my button clicked code :

$('#register-form').submit(function(event){
    var formData={
        'fn':$('#firstname').val(),
        'ln':$('#lastname').val(),
        'email':$('#email2').val(),
        'pass':$('#password2').val(),
        'action':'regUser'
    };
    $.ajax({
        type: 'POST',
        url: 'Index.php',
        data: formData,
        dataType: 'json',
        beforeSend: function () {
            $('#register-submit').attr("disabled","disabled");
            $("#divLoader").addClass("loader");
            console.log('before send');
        },
        success: function (data) {
            if(data.success){
                $('#success').fadeIn(1000).append('<p>'+data.userAdded+'</p>');
            }
            else{
                $('.throw_error').fadeIn(1000).html(data.errors[0]);
            }
        },
        error: function(){
            alert("System currently unavailable, try again later");
        },
        complete: function () {
            $('#register-submit').removeAttr('disabled');
            $('#divLoader').removeClass('loader');
        }
    });
    event.preventDefault();
});

What I want is that when I click on the submit button and there are validation problems that the button clicked event will not be triggered, so the AJAX call doesn't start.

Code Lღver

You have to put the condition before the ajax call. You have to check the form validation with the function valid() of jquery validate.

So your code will be like this:

$('#register-form').submit(function(event){
var formData={
    'fn':$('#firstname').val(),
    'ln':$('#lastname').val(),
    'email':$('#email2').val(),
    'pass':$('#password2').val(),
    'action':'regUser'
};
if($(this).valid()) {
    //ajax call  will be inside of this if condition
}

Reference link.

And make the debug: true,.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Submitting a form after validating with jquery validator on a button not in form tag

Form with two inputs not submitting?

Validating form then submitting to database with php

Validating different types of form inputs with criterias

Validating Dynamically Added Form Inputs - Vanilla JS

Validating repeating inputs inside an AngularJS form

Form clears after submitting

prevent enter submitting form, allow enter in inputs

Django - Submitting form with multiple inputs for same field

Form not submitting after form validation

Yii2 form validating but not submitting to send email

Unable to stop form from submitting when validating an email

Jquery form not submitting after validation

Vuetify reset form after submitting

Form not submitting after bootstrap confirmation

Loading a component after submitting a form

AJAX not submitting the form after validation

Empty modelAttribute after submitting a form

How to redirect after submitting form

Unable to clear the form after submitting

Multi-Part HTML Form Validating Only Some Inputs

How to call different post requests when submitting different form inputs

Remove duplicate form inputs while serializing and submitting two or more forms

Two inputs not submitting both values on form React js

display error message after submitting a form

Go to the url of the selection after submitting the form

redirecting a reactive form in angular after submitting

Variable isn't changing after form submitting

How to clean a form with stars in javascript after submitting?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive