Bryan Wong
Bryan Wong

Reputation: 633

AJAX with validation engine

It does not validate before AJAX call to send information to DB. How can i activate the Validation first?

$(document).ready(function() {
        $("#signup").validationEngine('attach', {
            promptPosition : "centerRight",
            scroll : false,
            ajaxFormValidation: true,
            onBeforeAjaxFormValidation: beforeCall,
            onAjaxFormComplete: ajaxValidationCallback,
        });
    });




$("#submit").click(function() {
        var url = "insertintoDB.php"; // the script where you handle the form input.
        $.ajax({
               type: "POST",
               url: url,
               data: $("#signupform").serialize(), // serializes the form's elements.
               success: function(data)
               {
                   alert(data); // show response from the php script.
               }
             });

        return false; // avoid to execute the actual submit of the form.
    });

It does direct to insertintoDB.php but does not validate the following form.

<form class="form-horizontal" id="signup" name="signup" method="post" action="insertDB.php">

 <div class="control-group">
 <label class="control-label" for="inputSurname">Name</label>
 <div class="controls"><input type="text" id="inputSurname" name="inputSurname" placeholder="Surname" class="validate[required]" /></div>
 </div>
<button type="submit" id="submit" class="btn btn-success">Sign Up!</button>

</form>

How can I make it validate first before passing into the PHP for data insertion?

Upvotes: 1

Views: 863

Answers (2)

Cliff Ribaudo
Cliff Ribaudo

Reputation: 9039

Use the jQuery Validator for form validation, with a pattern something like this:

$('form').validate({
    invalidHandler: function(event, validator) {
        // Handle the invalid case.
    },
    submitHandler: function(form) {
       // do stuff on your valid form.
       // Then call form submit.
       form.submit();
    }
});

The validator allows you to set up rules and error messages for various conditions, however it automatically detects missing fields with the 'required' attribute on them and other cases based on type of field. E.g. url - it will require a valid url, etc.

Server side validation is important, but the jQuery validator allows you to catch many things while you still have the users attention and they can easily fix.

See here: jQuery Validator

Upvotes: 0

Siamak Motlagh
Siamak Motlagh

Reputation: 5146

You can validate your variables using these validation open source libraries:

jQuery-Form-Validator
Lightweight form validation for jQuery or Zepto.js
jQuery-Validation-Engine

And so on ...

But i strongly recommend you use server side validation before do any database action to prevent SQL-injection and XSS attack.

Upvotes: 1

Related Questions