How to send an ajax validation only if jQuery validation plugin succeed? - javascript

I used jQuery validation plugin to validate form fields. Now I want to send an ajax request only if the fields are valid, which means after jQuery validation plugin succeed.
JavaScript:
$(function(){
$("#form").validate({
errorPlacement: function(label, element) {
label.addClass('arrow');
label.insertAfter(element);
},
wrapper: 'span',
rules: {
email: {
required: true,
email: true
},
name: {
required: true,
minlength: 5
},
password: {
required: true,
minlength: 6
},
rePassword:{
required: true,
minlength: 6,
equalTo: "#password"
},
birthDate:{
required: true
},
aboutYou:{
required: true
}
},
messages:{
email: {
required: "this field is required!",
email: "please enter a valid email!"
},
name:{
required: "this field is required!",
minlength: "name needs to have at least 5 chars!"
},
password:{
required: "password is required!",
minlength: "password needs to have at least 6 chars!"
},
rePassword:{
required: "rePassword is required!",
minlength: "rePassword needs to have at least 6 chars!",
equalTo: "passwords don't match!"
}
}
});
});
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<meta charset="utf-8">
<script src="includes/jquery-1.11.3.js"></script>
<link rel="stylesheet" type="text/css" href="css/css.css">
<script src="js/jquery.validate.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/registerForm.js"></script>
<?php
require_once'includes/DAL.php';
?>
<script>
$(function(){
$( "#form" ).submit(function(){
// run this code only if validation plugin succeed?
$.ajax({
method: "post",
url: "API.php",
data:{email: $("#email").val(), name: $("#name").val(), password: $("#password").val(), rePassword: $("#rePassword").val(), birthDate: $("#birthDate").val(), aboutYou: $("#aboutYou").val()},
success: function(result){$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<form method="post" id="form">
<label>Email</label><br/>
<input type="text" name="email" id="email" placeholder="Enter your email"/><br/>
<label>Name</label><br/>
<input type="text" name="name" id="name" placeholder="Enter your name"/><br/>
<label>Password</label><br/>
<input type="password" name="password" id="password" placeholder="Enter your password"/><br/>
<label>re-Password</label><br/>
<input type="password" name="rePassword" id="rePassword" placeholder="Repeat password"/><br/>
<label>Birth Date</label><br/>
<input type="date" name="birthDate" id="birthDate"/><br/>
<label>About yourself</label><br/>
<textarea name="aboutYou" id="aboutYou" placeholder="About yourself..."></textarea>
<input type="submit" id="submit" value="Register!"/>
<div id="div1"></div>
</form>
</body>
</html>

im guessing you are using the following plugin: http://jqueryvalidation.org/documentation/
And what you are looking for is probably this:
submitHandler (default: native form submit)
Type: Function()
Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it is validated.
So you can do something like this
$(".selector").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
});
API docs: http://jqueryvalidation.org/validate
======================
If that's not the plugin that you are using, look for something like this:
"Callback for handling the actual submit when the form is valid." in the plugin API docs. It's definitely gonna be implemented as a callback or a promise object.

Append function(errors, event) to your initail validator plugin script.
$(function(){
$("#form").validate({
errorPlacement: function(label, element) {
label.addClass('arrow');
label.insertAfter(element);
},
wrapper: 'span',
rules: {
email: {
required: true,
email: true
},
name: {
required: true,
minlength: 5
},
password: {
required: true,
minlength: 6
},
rePassword:{
required: true,
minlength: 6,
equalTo: "#password"
},
birthDate:{
required: true
},
aboutYou:{
required: true
}
},
messages:{
email: {
required: "this field is required!",
email: "please enter a valid email!"
},
name:{
required: "this field is required!",
minlength: "name needs to have at least 5 chars!"
},
password:{
required: "password is required!",
minlength: "password needs to have at least 6 chars!"
},
rePassword:{
required: "rePassword is required!",
minlength: "rePassword needs to have at least 6 chars!",
equalTo: "passwords don't match!"
}
},
function(errors, event) {
if (!errors.length) _submit();
}
});
});
function _submit() {
$( "#form" ).submit(function(){
$.ajax({
method: "post",
url: "API.php",
data:{email: $("#email").val(), name: $("#name").val(), password: $("#password").val(), rePassword: $("#rePassword").val(), birthDate: $("#birthDate").val(), aboutYou: $("#aboutYou").val()},
success: function(result){$("#div1").html(result);
}});
});
}

Related

minlength input field validation - JQuery

I have the JQuery validations below that just ensure that something is written within the input fields, I also have maxlength in the html.
However, I was hoping someone could shed some light on the situation and inform me on how I can add some type of minlength to the jquery code below so I don't require to do any additional functions?
$('#form1').submit(function (e) {
e.preventDefault();
}).validate({
rules: {
txtusername: {
required: true
},
txtfirstname: {
required: true
},
txtemail: {
required: true
},
txtpassword: {
required: true
},
passwordconfirm: {
required: true
}
},
messages: {
txtusername: {
required: "Please enter your Username."
},
txtfirstname: {
required: "Please enter your First Name."
},
txtemail: {
required: "Please enter your Email."
},
txtpassword: {
required: "Please enter your Password."
},
passwordconfirm: {
required: "Please enter your password again."
}
},
errorPlacement: function (error, element) {
error.appendTo(element.parent().prev());
},
submitHandler: function (form, user) {
CheckUser(form);
return false;
}
});
Example HTML -
<div data-role="fieldcontainer">
<label for="txtusername" data-theme="d">Username:</label>
<input type="text" id="txtusername" name="txtusername" maxlength="12" placeholder="Enter Username"/>
</div>
You can use like below:
rules:{
txtusername: {
required: true,
minlength: 3
},
}

Unable to match password using equalTo property

I want to validate my form using validate.js and match the password. I wrote the following code:
$(document).ready(function () {
$("#signup-form").validate({
rules: {
"signup-username": {
required: true,
minlength: 2
},
"signup-firstname": {
required: true,
minlength: 2
},
"signup-lastname": {
required: true,
minlength: 2
},
"signup-email": {
required: true
},
"signup-password1": {
required: true,
minlength: 5
},
"signup-password2": {
equalTo: "#signup-password1"
}
},
messages: {
"signup-username": {
required: "Please, enter a user name",
minlength: "Minimum userlength should be 2"
},
"signup-firstname": {
required: "Please, enter your first name",
minlength: "Minimum firstname length should be 2"
},
"signup-lastname": {
required: "Please, enter your last name",
minlength: "Minimum lastname length should be 2"
},
"signup-email": {
required: "Please, enter a valid email"
},
"signup-password1": {
required: "Please, enter your password",
minlength: "Minimum password length should be 5"
},
"signup-password1":"Password doesn't match."
}
submitHandler: function (form)
{
alert("form is submitted successfully.");
}
});
});
I am new to js. Why is it not working. Sometimes I wonder where to put comma and where not. Please help me.
Try change:
"signup-password2": {
equalTo: "#signup-password2"
}
...
"signup-password1":"Password doesn't match."
to:
"signup-password2": {
required: true,
equalTo: "#signup-password1"
}
...
"signup-password2": {
required: "Please, enter your password again",
equalTo: "Password doesn't match."
}
Doc
jsfiddle- validate plugin is broken
another fiddle - works correct
not familiar at all with this library, but I think you mean to check whether signup-password2 is equal to signup-password1. So it should read like:
"signup-password2": {
equalTo: "#signup-password1"
}

jQuery validation not working with that form

I have been trying to validate a form with jquery validate plugin.As a newbie i am facing problem with that.Here is the code
$(document).ready(function() {
$("#log-form").validate({
errorElement: 'div',
rules: {
"username": {
required: true,
minlength: 5
},
"password": {
required: true,
minlength: 5
}
},
messages: {
username: {
required: "Provide a username,sire",
minlength: "Username with length 5 atleast,is required"
},
password: {
required: "Provide a password,sire",
minlength: "Minimum length of 5 is required for password,sire"
}
}
submitHandler: function(form) {
form.submit();
}
});
});
<form name="log-form" id="log-form" method="post" action="check_login.php">
<label for="username">Username</label>
<input type="text" class="" id="username" name="username">
<br>
<label for="password">Password</label>
<input type="password" class="" id="password" name="password">
<br>
<button type="submit" name="sub-btn" class="sub-btn">Login</button>>
</form>
The validation is not working as i change field after typing in one neither on submiting the form.
As per #unidentified: There is a syntax error in your code, missing , after the messages property. Please check How can I debug my JavaScript code?
$(document).ready(function() {
$("#log-form").validate({
errorElement: 'div',
rules: {
"username": {
required: true,
minlength: 5
},
"password": {
required: true,
minlength: 5
}
},
messages: {
username: {
required: "Provide a username,sire",
minlength: "Username with length 5 atleast,is required"
},
password: {
required: "Provide a password,sire",
minlength: "Minimum length of 5 is required for password,sire"
}
}, // syntax error, comma was missing here
submitHandler: function(form) {
form.submit();
}
});
});

Validation success control

Here is my code. My main problem is that var validationbool triggers success even if only one field of contact form is valid and it does not care if the other ones are invalid. How can I create better control that var validationbool = true only when all elements are valid.
$(document).ready(function () {
var validationBool = false;
$('#register-form').validate({
rules: {
name: {
minlength: 3,
required: true
},
email: {
required: true,
email: true
},
phone: {
required: true,
minlength: 10
},
country: {
required: true
},
boat: {
required: true
},
lat: {
required: true
},
registration: {
required: true
},
file: {
required: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
validationBool = false;
},
success: function (element) {
element.text('').addClass('valid').closest('.control-group').removeClass('error').addClass('success');
validationBool = true;
}
});
$('#register-form').on('submit', function(e){
e.preventDefault();
if(validationBool){
var theData = {
name: $('#name').val(),
phone: $('#phone').val(),
email: $('#email').val(),
country: $('#country').val(),
lat: $('#lat').val(),
lng: $('#lng').val(),
boat: $('#boat').val(),
registration: $('#registration').val(),
file: $('#file').val()
};
$.ajax({ // ajax call starts
url: "functions/enroll.php",
type: 'post',
data: theData,
success: function(data)
{
swal("Your request has been recieved!", "We will contact you for confirmation soon", "success");
document.getElementById('name').value='',
document.getElementById('phone').value='',
document.getElementById('email').value='',
document.getElementById('country').value='',
document.getElementById('lat').value='',
document.getElementById('lng').value='',
document.getElementById('boat').value='',
document.getElementById('file').value='',
document.getElementById('registration').value='';
}
});
}
});
});
I would use the .valid() mehthod.
This would be printed like
var myForm = $("#register-form");
myForm.validate();
then, instead of using the "validationBool" variable, use
if (myForm.valid())
to check if the form is validated - this will check all fields.
Here is what I thought will work for you with validate():
[Note: This is just an example I used and you can use the similar approach - You don't have to explicitly use any boolean variable for knowing whether you can submit.
Do note, I used:
Invalidate Handler - Callback for custom code when an invalid form is submitted. Called with an event object as the first argument, and the validator as the second.
Submit Handler - Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it is validated.
Html code:
<form class="cmxform" id="commentForm" method="get" action="http://www.google.com">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" />
</p>
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" />
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url" />
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment"></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit" />
</p>
</fieldset>
</form>
JS code:
$("#commentForm").validate({
rules: {
name: {
minlength: 3,
required: true
},
email: {
required: true,
email: true
},
phone: {
required: true,
minlength: 10
},
country: {
required: true
},
boat: {
required: true
},
lat: {
required: true
},
registration: {
required: true
},
file: {
required: true
}
},
invalidHandler: function (event, validator) {
var errors = validator.numberOfInvalids();
/*Here you will get your errors
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("div.error span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}*/
alert(errors);
},
submitHandler: function (element) {
//Handler for submit action
//$(form).ajaxSubmit();
alert("submit");
}
});
JSFiddle Link here

jquery validation not firing

My form is using jquery validation. However, the validation is not firing. I am sure it is just a tiny mistake somewhere.. anyone?
Here is fiddle link http://jsfiddle.net/2L6xT/
BAsically here is my jquery validation code
$(document).ready(function () {
<!-- validation -->
$('#submitDetails').validate({
// 1. validation rules.
rules: {
firstName: {
required: true,
maxlength: 120
},
lastName:{
required: true,
maxlength: 120
},
custom1: {
required: true,
maxlength: 120
},
state: {
required: true
},
custom9: {
required: true
},
email: {
required: true,
email: true
}
},
// 2. Validation fail messages
messages: {
custom9: {
required: "You must agree to the terms of conditions in order to participate."
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "custom9" )
error.appendTo("#error_msg");
else
error.insertAfter(element);
}
});
///execute when submit button is clicked
$("#submit").click(function () {
});
});
In your html, the input element doesnot have name, the validator framework uses name to apply the rules
<input type="text" class="form-control" id="firstName" name="firstName" placeholder="First name" />
so along with id add name also(id is not required if it is not used elsewhere)
Demo: Fiddle

Categories