Why does jquery.validate.js show error messages twice? - javascript

I am trying to create form with jQuery validation and this is my form,
Then I am using this code to validate the inputs.
It's just plain and simple:
$('#forgot_pwd').validate({
debug: true,
rules: {
username: {
minlength: 6,
required: true,
},
email: {
required: true,
email: true
}
},
messages: {
username: {
required: "Enter your Username"
},
email: {
required: "Enter your Email",
email: "Enter valid email address"
},
},
errorPlacement: function(error, element) {
error.hide();
$('.messagebox').hide();
error.appendTo($('#alert-message'));
$('.messagebox').slideDown('slow');
},
highlight: function(element, errorClass, validClass) {
$(element).parents('.control-group').addClass('error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).parents('.control-group').removeClass('error');
$(element).parents('.control-group').addClass('success');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<div class="card">
<h4 class="l-login">Forgot Password</h4>
<div class="messagebox">
<div id="alert-message"></div>
</div>
<form class="col-md-12" id="forgot_pwd" method="POST">
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" id="username" name="username">
<label class="form-label">Username</label>
</div>
</div>
<div class="form-group form-float">
<div class="form-line">
<input type="email" class="form-control" id="email" name="email">
<label class="form-label">Email</label>
</div>
</div>
<button id="signin" type="submit" class="btn btn-raised waves-effect bg-red" data-loading-text="Loading...">Reset Password</button>
SIGN UP<br/><br/>
</form>
</div>
As for me I am calling the error message box only once but it shows up twice.
Not sure why it shows up twice.
why is that?

Try using the invalidHandler function to empty it.
invalidHandler: function() {
$('#alert-message').empty();
}
This will empty the #alert-message when the form is submitted and your rules fail. This will allow the errorPlacement function to be called multiple times without emptying #alert-message on multiple errors.
For example in your code.
$('#forgot_pwd').validate({
debug: true,
rules: {
username: {
minlength: 6,
required: true,
},
email: {
required: true,
email: true
}
},
messages: {
username: {
required: "Enter your Username"
},
email: {
required: "Enter your Email",
email: "Enter valid email address"
},
},
errorPlacement: function(error, element) {
error.hide();
$('.messagebox').hide();
error.appendTo($('#alert-message'));
$('.messagebox').slideDown('slow');
},
highlight: function(element, errorClass, validClass) {
$(element).parents('.control-group').addClass('error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).parents('.control-group').removeClass('error');
$(element).parents('.control-group').addClass('success');
},
invalidHandler: function() {
$('#alert-message').empty();
}
});

I think you should clear $('#alert-message') before adding new message to it.
errorPlacement: function(error, element) {
error.hide();
$('.messagebox').hide();
$('#alert-message').empty()
error.appendTo($('#alert-message'));
$('.messagebox').slideDown('slow');

Related

Can not run validation on a single element

I have created a form which has multiple input for each record and I hide/show them on demand.
The problem is when they are editable I want to validate the values without form submit.
<form action="Update" method="post" id="frmUpdateGroup" class="frmUpdateGroup">
<div>
<input id="Name_1" name="Name_1" required class="grp-Name form-control form-control-flat" value="zzzzz" />
</div>
<div style="display:none">
<input id="Name_2" name="Name_2" required class="grp-Name form-control form-control-flat" value="" />
</div>
var $updateGroupNameValidator;
$('.frmUpdateGroup').validate({});
$updateGroupNameValidator = $('.grp-Name').validate({
rules: {
minlength: 3,
maxlength: 50,
required: true
},
messages: {
required: "group name can not be null or empty",
minlength: "group name must be at least 3 characters long",
maxlength: "group name can not exceed 50 characters"
},
highlight: function(element) {
$(element).closest('.form-group').addclass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeclass('has-error');
},
errorelement: 'span',
errorclass: 'help-block',
errorplacement: function(error, element) {
debugger;
if (element.parent('.input-group').length) {
error.insertafter(element.parent());
} else {
error.insertafter(element);
}
}
});
$('.grp-Name').blur(function(e) {
$updateGroupNameValidator.valid();
});
$('.grp-Name').keyup(function(e) {
$updateGroupNameValidator.valid();
});
I have created the form JFiddle link and expect to see error when the first textbox is cleared or input text is less than 3 characters, but noıthing happens.
I'm not a guru of the validator plugin, but I think you can't define validator on a single element like you did, only defining rules for each element inside form validation handler like in the example below:
var validator = $("#frmUpdateGroup").validate({
// Specify the validation rules
rules: {
Name_1: {
required: true,
minlength: 3,
maxlength: 50
},
},
// Specify the validation error messages
messages: {
Name_1: {
required: "group name can not be null or empty",
minlength: "group name must be at least 3 characters long",
maxlength: "group name can not exceed 50 characters"
},
},
});
$('.grp-Name').keyup(function(e) {
$('#Name_1').valid();
// or $("#frmUpdateGroup").data('validator').element('#Name_1').valid();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
<form action="Update" method="post" id="frmUpdateGroup" class="frmUpdateGroup">
<div>
<input id="Name_1" name="Name_1" required class="grp-Name form-control form-control-flat" value="zzzzz" />
</div>
<div style="display:none">
<input id="Name_2" name="Name_2" required class="grp-Name form-control form-control-flat" value="" />
</div>
</form>

Hide success and error messages on form

I have one subscription form with ajax. The problem is that success and error messages are always on the page. Why they are on the page and how to hide them until form is submitted?
This is my js function
$(document).ready(function(){
(function($) {
"use strict";
// validate subscribeForm form
$(function() {
$('#subscribeForm').validate({
rules: {
name: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
}
},
messages: {
name: {
required: "Please enter your name?",
minlength: "Your name must consist of at least 4 characters"
},
email: {
required: "Please enter your email address"
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"subscribe.php",
success: function() {
$('#subscribeForm :input').attr('disabled', 'disabled');
$('#subscribeForm').fadeTo( "slow", 0.15, function() {
$(this).find(':input').attr('disabled', 'disabled');
$(this).find('label').css('cursor','default');
$('#sub_success').fadeIn();
});
},
error: function() {
$('#subscribeForm').fadeTo( "slow", 0.15, function() {
$('#sub_error').fadeIn();
});
}
})
}
})
})
})(jQuery)
})
And this is the form
<div class="footer-newsletter row footer-widget right-box">
<h3 class="footer-title">newsletter sign up</h3>
<form class="form-inline newsletter-form" id="subscribeForm" method="post" action="">
<input type="text" id="name" name="name" class="form-control" placeholder="Name">
<input type="email" id="email" name="email" class="form-control" placeholder="Email">
<button type="submit" class="btn btn-primary" name="sub_submit">Submit</button>
</form>
<div id="sub_success">You subscribe succesfully!</div>
<div id="sub_error">Opps! There is something wrong. Please try again</div>
</div>
So sub_success and sub_error are always on the page..
Change this following things in your code:-
<div id="sub_success" style="display:none">You subscribe succesfully!</div>
<div id="sub_error" style="display:none">Opps! There is something wrong. Please try again</div>
use this type alert it will gone in 3sec
$('#success_message').fadeIn(1000).html("<div class='alert alert-danger' role='alert' style='font-size: 15px;'>Soory some there is some error,please enter again data...</div>").fadeOut(3000);
Just add .hide on document.ready for both elements as below:
$(document).ready(function(){
$('.sub_success,.sub_error').hide();
});
You could just write a css
#sub_success, #sub_error {display:none}
then with jquery you can just show and hide by using
$("#sub_success").show();
$("#sub_error").hide();

JQuery validate not showing error

for some reason having issues with JQuery validate even though I have used similar code previously. I have a simple form.
<form id="emailform" class="form-horizontal emailType" role="form">
<div class="form-group">
<label for="inputTitle" class="col-lg-4 control-label">Title</label>
<div class="col-lg-8">
<select class="form-control" id="inputTitle" name="inputTitle">
<option value="">Please select...</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputName" class="col-lg-4 control-label">First Name(s)</label>
<div class="col-lg-8">
<input type="text" class="form-control" id="inputName" name="inputName" placeholder="First Name(s)">
</div>
</div>
<div class="form-group">
<label for="inputSurname" class="col-lg-4 control-label">Surname</label>
<div class="col-lg-8">
<input type="text" class="form-control" id="inputSurname" name="inputSurname" placeholder="Surname">
</div>
</div>
<div class="form-group">
<label for="inputMethod" class="col-lg-4 control-label">Delivery Method</label>
<div class="col-lg-8" id="radioAlign">
<input type="radio" value="email" id="inputMethod" checked><span id="emailText">Email</span>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-lg-4 control-label">Email</label>
<div class="col-lg-8">
<input type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email">
</div>
</div>
<div class="form-group">
<label for="inputLinks" class="col-lg-4 control-label">Link to be sent</label>
<div class="col-lg-8">
<select class="form-control" id="inputLinks" name="inputLinks">
<option value="img/default.jpg">Please select...</option>
<option value="img/placeholder.jpg">Email1</option>
<option value="img/placeholder2.jpg">Email2</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-default">
Send Message
</button>
</div>
</div>
</form>
<div id="error"></div>
I then have my validation.
$.validator.addMethod(
"notEqualTo",
function(elementValue,element,param) {
return elementValue != param;
},
"Value cannot be {0}"
);
$.validator.addMethod("myCustomRule", function(value, element) {
return /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{1,}))$/.test(value);
}, "Please enter a valid email");
var validator = $("#emailform").validate({
errorPlacement: function (error, element) {
$(element)
.closest("form")
.find("#error")
.append(error);
},
rules: {
inputTitle: {
required: true,
notEqualTo: "Please select..."
},
inputName: {
required: true,
minlength: 1
},
inputSurname: {
required: true,
minlength: 1
},
inputEmail: {
required: true,
myCustomRule: true,
minlength: 5,
email: true
},
inputLinks: {
required: true,
notEqualTo: "Please select..."
}
},
messages: {
inputName: {
minlength: jQuery.validator.format("Please enter a valid name")
},
inputSurname: {
minlength: jQuery.validator.format("Please enter a valid surname")
},
inputEmail: {
minlength: jQuery.validator.format("Your email address is to short")
}
},
submitHandler: function(){
//Do success stuff here
return true;
},
invalidHandler: function(event,validator) {
//do error stuff here
return false;
}
});
If I submit the form, my error message does not display. Instead, the input gets highlighted with a blue border.
Is there any reason my errors do not display?
Thanks
I have update your validation massage code;
Please check this,
$.validator.addMethod(
"notEqualTo",
function(elementValue,element,param) {
return elementValue != param;
},
"Value cannot be {0}"
);
$.validator.addMethod("myCustomRule", function(value, element) {
return /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{1,}))$/.test(value);
}, "Please enter a valid email");
var validator = $("#emailform").validate({
errorPlacement: function (error, element) {
$(element)
.closest("form")
.find("#error")
.append(error);
},
rules: {
inputTitle: {
required: true,
notEqualTo: "Please select..."
},
inputName: {
required: true,
minlength: 1
},
inputSurname: {
required: true,
minlength: 1
},
inputEmail: {
required: true,
myCustomRule: true,
minlength: 5,
email: true
},
inputLinks: {
required: true,
notEqualTo: "Please select..."
}
},
messages: {
inputName: {
minlength: jQuery.validator.format("Please enter a valid name")
},
inputSurname: {
minlength: jQuery.validator.format("Please enter a valid surname")
},
inputEmail: {
minlength: jQuery.validator.format("Your email address is to short")
}
},
errorPlacement: function (label, element) { // render error placement for each input type
$('<span class="error"></span>').insertAfter(element).append(label)
var parent = $(element).parent('.input-with-icon');
parent.removeClass('success-control').addClass('error-control');
},
highlight: function (element) { // hightlight error inputs
var parent = $(element).parent();
parent.removeClass('success-control').addClass('error-control');
},
unhighlight: function (element) { // revert the change done by hightlight
var parent = $(element).parent();
parent.removeClass('error-control').addClass('success-control');
},
submitHandler: function(){
//Do success stuff here
return true;
},
invalidHandler: function(event,validator) {
//do error stuff here
return false;
}
});
does it work or not? let me know

Form is not validate using validate.min.js

Hi I succeed to make this code works but I don't know why this code is not working anymore anyone can help please on this?
Here this is my form
<form action="CreateUser" method="POST" id="subscribe">
<br>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><b>#</b></span>
<label for="mail"></label>
<input type="text" class="form-control" name="mail" id="mail" placeholder="Adresse mail">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-user"></span></span>
<label for="firstname"></label>
<input type="text" class="form-control" name="firstname" id="firstname" placeholder="Entrez votre prenom">
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-user"></span></span>
<label for="name"></label>
<input type="text" class="form-control" name="name" id="name" placeholder="Entrez votre nom">
</div>
</div>
<div class="form-group">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-lock"></span></span>
<label for="inputPassword"></label>
<input id="inputPassword" name="inputPassword" type="password" class="form-control" placeholder="Mot de passe">
</div>
</div>
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-lock"></span></span>
<label for="txtConfirmPassword"></label>
<input id="txtConfirmPassword" name="txtConfirmPassword" type="password" class="form-control" placeholder="Retapez votre mot de passe">
</div>
</div>
<br>
<div class='modal-footer'>
<button class="btn btn-lg btn-success btn-block" name="submit" id="register" >Creer votre compte</button>
</div>
</form>
And here this the validate function I did:
<script>
$.validator.setDefaults({
debug: true,
success: "valid",
highlight: function (element) {
$(element).parent().removeClass('has-success').addClass('has-error');
},
unhighlight: function (element) {
$(element).parent().removeClass('has-error').addClass('has-success');
},
errorElement: 'span',
errorClass: 'text-danger',
errorPlacement: function (error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$.validator.addMethod("onlyletters", function (value, element) {
return this.optional(element) || /^[a-zA-ZáàâäãåçéèêëíìîïñóòôöõúùûüýÿæœÁÀÂÄÃÅÇÉÈÊËÍÌÎÏÑÓÒÔÖÕÚÙÛÜÝŸÆŒ._\s-]+$/i.test(value);
}, "Please enter letters only.");
$.validator.addMethod("passwd", function (value, element) {
return this.optional(element) || /^[a-zA-Z0-9]+$/i.test(value);
}, "Please enter letters and numbers only.");
$('#subscribe').validate({
rules: {
inputPassword: {
required: true,
minlength: 6,
maxlength: 12,
passwd: true
},
txtConfirmPassword: {
required: true,
minlength: 6,
maxlength: 12,
passwd: true,
equalTo: "#inputPassword"
},
mail: {
required: true,
email: true
},
firstname: {
required: true,
maxlength: 20,
onlyletters: true
},
name: {
required: true,
maxlength: 20,
onlyletters: true
}
},
messages: {
inputPassword: {
required: "Password is required",
minlength: "Your password must have 6 characters."
},
txtConfirmPassword: {
required: "Password is required",
minlength: "Your password must have 6 characters.",
equalTo: "Your password doesn't match."
},
mail: {
required: "Email is required",
email: "Your mail address should be like user#example.com"
}
}
});
$('#register').click( function() {
// Error checking here.
if ($('div.error').is(':visible')) {
return false;
}else{
}
});
</script>
And the imported jquery plugin
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
The plugin are imported from a previous page index.html and this form is loading from a modal
There is a problem on your .click() syntax, here is the working code in a JSFiddle.
Your error was a } and ) problem.
Your click event handler is not correct.
$('#register').click( function() {
// Error checking here.
if ($('div.error').is(':visible')) {
return false;
}else{
});// This needs to be removed!!!!!
}
});
Working code:
$('#register').click( function() {
// Error checking here.
if ($('div.error').is(':visible')) {
return false;
} else {
}
});

Display form values in another div(display) using jquery on submit

It is an easy code. Maybe using $().html() or .text().
Since Iam new to jquery so plz an easy to understand code.
Inspite of searching on previous similar posts I am still confused.
Do I need to create another js file or I have to make changes in the existing js file.
Guys if possible plz provide a jquery code.
(function($, W, D {
var JQUERY4U = {};
JQUERY4U.UTIL = {
setupFormValidation: function() {
$("#form").validate({
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
bio: "required",
password: {
required: true,
minlength: 5
},
passwordcp: {
equalTo: "#password"
}
},
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
passwordcp: "Password not matching",
email: "Please enter a valid email address",
},
submitHandler: function(form) {
form.submit();
}
});
}
}
$(D).ready(function($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
HTML
<form action="" id="form" >
<div class="formelement">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname"/>
</div>
<div class="formelement">
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname"/>
</div>
<div class="formelement">
<label for="email">Email-ID</label>
<input type="text" name="email"/>
</div>
<div class="formelement">
<label for="bio">BIO</label>
<textarea rows="3" cols="30" name="bio"></textarea>
</div>
<div class="formelement">
<label for="password">Password</label>
<input type="password" name="password" id="password" />
</div>
<div class="formelement">
<label for="passwordcp">Confirm-Password</label>
<input type="password" name="passwordcp" id="passwordcp" />
</div>
<div class="formelement">
<input type="submit" value="SUBMIT" class="submit"/>
</div>
</form>
<div class="display"></div>
I would just do it like this, see it in action here: http://jsfiddle.net/awsxtkd0/
$(document).ready(function() {
$("#form").validate({
rules: {
firstname: "required",
lastname: "required",
email: {
required: true,
email: true
},
bio: "required",
password: {
required: true,
minlength: 5
},
passwordcp: {
equalTo: "#password"
}
},
messages: {
firstname: "Please enter your first name",
lastname: "Please enter your last name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
passwordcp: "Password not matching",
email: "Please enter a valid email address",
}
});
$('#form').submit(function() {
if($('#form').valid()) {
var str = '';
str += $('#firstname').val() + '<br />';
str += $('#lastname').val() + '<br />';
str += $('#email').val() + '<br />';
str += $('#bio').val() + '<br />';
$('.display').append(str);
}
return false;
});
});

Categories