updating jqbootstrapvalidation match to validate only on form submit - javascript

How can i change the jqbootstrapvalidation's match to match only on form submit. like the required fields match is carried out. lets say i have a password and retype password field. when i click the password field it says in error box of retype password that "Match validation failed"
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<!--<script type="text/javascript" src="js/jquery.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="js/test.js"></script>
<script>
$(function () { $("input,select,textarea").not([type=submit]").jqBootstrapValidation(); });</script><title</title></head><body>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">Password</label>
<div class="controls">
<input type="password" name="password1" required="required" />
<p class="help-block"></p>
</div>
</div>
<div class="control-group">
<label class="control-label">Retype Password</label>
<div class="controls">
<input type="password" data-validation-match-match="password1" name="password2" required="required" />
<p class="help-block"></p>
</div>
</div>
Submit: <input type="submit" name="submitbtn" id="submitbtn" value="submit" />
</form>
</body>
</html>
how can i make the change so that match validation applies only on form submit. any help will be highly appreciated.
Many thanks in advance.

I did this by editing the jqBootstrapvalidation.js.
On validation.validation, params.submitting determines it is a submit.
I needed to execute a ajax, with BD access. So I created a new "validator" (in validatorTypes: ajax_v2), with a new property (somenteSubmit) to indicate that it's only used at a submit.
In the begin of js, including a new option:
(function( $ ){
var createdElements = [];
var defaults = {
options: {
somenteSubmit:false,//indicates the validator will happen only in submit
prependExistingHelpBlock: false,
sniffHtml: true, // sniff for 'required', 'maxlength', etc
preventSubmit: true, // stop the form submit event from firing if validation fails
submitError: false, // function called if there is an error when trying to submit
submitSuccess: false, // function called just before a successful submit event is sent to the server
semanticallyStrict: false, // set to true to tidy up generated HTML output
autoAdd: {
helpBlocks: true
},
filter: function () {
// return $(this).is(":visible"); // only validate elements you can see
return true; // validate everything
}
},
in validation.validation:
// =============================================================
// VALIDATION
// =============================================================
$this.bind(
"validation.validation",
function (event, params) {
var value = getValue($this);
var validar = true;
// Get a list of the errors to apply
var errorsFound = [];
$.each(validators, function (validatorType, validatorTypeArray) {
if (value || value.length || (params && params.includeEmpty) || (!!settings.validatorTypes[validatorType].blockSubmit && params && !!params.submitting)) {
$.each(validatorTypeArray, function (i, validator) {
validar=true;
if ((!(params && params.submitting)) && (settings.validatorTypes[validatorType].somenteSubmit)) {
validar=false;
}
if (validar){
if (settings.validatorTypes[validatorType].validate($this, value, validator)) {
errorsFound.push(validator.message);
}
}
});
}
});
return errorsFound;
}
);
On ValidatorTypes:
ajax_v2: {
name: "ajax_v2",
init: function ($this, name) {
return {
validatorName: name,
url: $this.data("validation" + name + "Ajax_v2"),
lastValue: $this.val(),
lastValid: true,
lastFinished: true
};
},
validate: function ($this, value, validator) {
validator.lastValue = value;
validator.lastValid = true;
validator.lastFinished = false;
var resultado= $.ajax({
url: validator.url+value,
data: ({}),
dataType: "html",
async :false
}).responseText; ;
if (resultado=="true") {
return true;
}else {
return false;
}
},
blockSubmit: true,
somenteSubmit:true //execute this new validator only in submit .
},
JSP:
<td>Login</td>
<td>
<div class="control-group">
<div class="controls">
<input class="form-control" type="text" autofocus="" id="login" name="usuario.login" value="${usuario.login}" size="25" placeholder="Login" required=""
data-validation-regex-regex="^[A-Za-z\d]{8,10}$"
data-validation-regex-message="O Login deve conter entre oito a dez caracteres (letras ou números)."
data-validation-nevermatches-nevermatch="usuario.idCliente"
data-validation-nevermatches-message="Login não deve ser igual ao Cartão."
data-validation-ajax_v2-ajax_v2="${pageContext.request.contextPath}/pesquisaLogin/"
data-validation-ajax_v2-message="Login já existente. Favor informar outro Login."
>
<div class="help-block"></div>
</div>
</div>
</td>

Related

I can not trigger the alert when the form is empty after developing a clean code in pure JavaScript

The small code in pure HTML, without forgetting to set the method for get:
<form action="#" method="get">
<input id="name" type="text" name="name" placeholder="Nome"><br>
<input id="email" type="text" name="email" placeholder="E-mail"><br>
<textarea id="message" name="name" rows="8" placeholder="Dê-nos um elogio, uma reclamação ou um elogio"></textarea>
<input type="submit" value="Enviar" id="send"><br>
</form>
I refactored and made a clean code of the dirty multiple if-else statements, simplifying. After it, I can not trigger the alert.
The code let send = document.getElementById("send"); checks the code <input type="submit" value="Enviar" id="send"><br>.
Before, in a dirty code, I had many document.getElementById("email").value == "" and simplified to:
const fields = new Set([
'name',
'email',
'message',
]);
I simplified three 'if-else statements along with these if-else statements of identifiers. Firstly, it will check if the fields are empty, go to verify the length, 1 indicates only an empty field and > 1 indicates more empty fields. Else they will check the fields are full and submit.
function alert()
{
let required = fields.value == "";
if (required.length == 1)
{
alert("The field is required!");
required = []
}
else if (required.length > 1)
{ alert("The fields are required!");
required = []
}
else
{
document.getElementById("send").submit();
alert("Thank you! The message was sent successfully")
}
}
Finally, the code send.addEventListener("click", alert) indicates to click the function when sending, and addEventListener will trigger the alert.
Complete code in JavaScript:
let send = document.getElementById("send");
const fields = new Set([
'name',
'email',
'message',
]);
function alert()
{
let required = fields.value == "";
if (required.length == 1)
{
alert("The field is required!");
required = []
}
else if (required.length > 1)
{ alert("The fields are required!");
required = []
}
else
{
document.getElementById("send").submit();
alert("Agradecemos, mensagem enviada com sucesso!")
}
}
send.addEventListener("click", alert)
I will suggest that you create an event listener for invalid on the form. This will be called when one of the required fields empty/invalid (see the required attribute on all the fields). I made a custom alert that shows.
var alert = document.getElementById('alert');
alert.addEventListener('click', e => {
if (e.target.nodeName == 'BUTTON')
alert.classList.remove('show');
});
document.forms.form01.addEventListener('submit', e => {
console.log('The form will submit');
});
document.forms.form01.addEventListener('invalid', e => {
e.preventDefault();
alert.classList.add('show');
}, true);
#alert {
display: none;
}
#alert.show {
display: block;
}
<form name="form01" action="#" method="get">
<input id="name" type="text" name="name" placeholder="Nome" required><br>
<input id="email" type="text" name="email" placeholder="E-mail" required><br>
<textarea id="message" name="message" rows="8" placeholder="Dê-nos um elogio, uma reclamação ou um elogio" required></textarea>
<input type="submit" value="Enviar" id="send"><br>
</form>
<div id="alert">The fields are required! <button>OK</button></div>
This is overruling the default behavior in the browser. In any case I think the required attribute is the right way to go.
You may like to do something like this with your function:
function showAlerts(){
var allInputs = document.querySelectorAll('#name, #email, #message');
if(null != allInputs){
for(var i in allInputs){
if(!isNaN(i)){
// here you can check for values, emptiness etc
if(allInputs[i].value.trim() === ''){
// this field is empty
alert('This field is required!');
}
...
}
}
}
}

jQuery Validator Add method not working

I'm using jquery validator addmethod for validation. While clicking the .btn-md button event fires and shows the alert that I've given. But the addmethod was not working.
HTML Code:
<div class="container">
<div class="lg_cont">
<h2>Reset your Password</h2>
<form method="post" class="lg_form" name="lg_form" id="formresetpwd">
<p class="lg_inp"><label for="pwd">Password <span>*</span></label>
<!--<span><i class="fa fa-lock"></i></span>-->
<input type="password" name="pwd" id="pwd" class="txt"/>
</p>
<p class="lg_inp">
<label for="lg_pass">Retype Password <span>*</span></label>
<!--<span><i class="fa fa-lock"></i></span>-->
<input type="password" name="rpwd" id="rpwd" class="txt"/>
</p>
<p><label style="font-size:13px;" id="psw_hint" class="hint" for="psw_hint"><span>*</span>Password should atleast contain 6 characters with Alphabet, Numeric and Underscores.</label></p>
<p><button type="submit" class="btn btn-success btn-md">Submit</button></p>
<?php if (isset($msg)) { ?>
<p><?php echo $msg; ?></p>
<?php } ?>
</form>
</div>
</div>
Jquery:
$('.btn-md').on('click', function () {
alert('test');
$('#formresetpwd').validate({
rules: {
pwd: {
required: true,
minlength: 6,
LowserCase: true,
Digit: true,
Special_char: true
}
},
messages: {
pwd: {
required: "password is required",
minlength: "Enter atleast 6 characters"
}
},
});
});
$.validator.addMethod("Uppercase", function (value, element) {
return this.optional(element) || /[A-Z]/.test(value);
}, "Enter atleast one Capital letter");
$.validator.addMethod("LowserCase", function (value, element) {
return this.optional(element) || /[a-z]/.test(value);
}, "Enter atleast one Small letter");
$.validator.addMethod("Digit", function (value, element) {
return this.optional(element) || /[0-9]/.test(value);
}, "Enter atleast one Number");
$.validator.addMethod("Special_char", function (value, element) {
return this.optional(element) || /[{}|~`"'[\]$&+,:;=?##|'<>.^*()%!-]/.test(value);
}, "Enter atleast one Special Character");
Thanks in advance.
Your code...
$('.btn-md').on('click', function () {
alert('test');
$('#formresetpwd').validate({
....
While clicking the .btn-md button event fires and shows the alert that I've given. But the addmethod was not working.
Based on your code, you click the button and the alert fires, then the .validate() method is called. Nothing else is supposed to happen.
The .validate() method is not for triggering validation; it's only used to initialize the plugin on your form. It does not belong inside of a click handler. The plugin already captures the click of the submit button and automatically triggers any necessary validation.
$(document).ready(function() {
$('#formresetpwd').validate({ // <- INITIALIZE plugin
rules: {
....
},
....
});
$.validator.addMethod( ....
});
Working DEMO: jsfiddle.net/9vgpLmt5/
you have to set input element class="pwd"
<input type="password" name="pwd" id="pwd" class="txt pwd"/>

jQuery : How to do validation in jquery before submit the form?

I have a form bootstrap form like below
<form id="loginForm" method="post" action="" role="form" class="ajax">
<div class="form-group">
<label for="userName"></label>
<input type="text" class="form-control" id="usrName">
</div>
<div class="form-group">
<label for="passWrd"></label>
<input type="password" class="form-control" id="passWrd">
</div>
<div class="form-group">
<button class="btn btn-default" type="button" id="loginButton">Login</button>
</div>
I am doing form validation in my jquery as below. How do I call submit() method in my code? i.e how do I make ajax call to submit the form content after validation in the jQuery.
$(document).ready(function() {
function validateInput(id) {
if($("#"+id).val()==null || $("#"+id).val()=="") {
var div=$("#"+id).closest("div");
div.addClass("has-error");
return false;
} else {
var div=$("#"+id).closest("div");
div.removeClass("has-error");
div.addClass("has-success");
return false;
}
}
$(#loginButton).click(function() {
enter code here
if(!validateInput("userName"))
{
return false;
}
if(!validateInput("passWrd"))
{
return false;
}
});
});
How do i call $.ajax after i complete the validation in my above code?
P.S : I am not supposed to use any jquery plugin for the validation.
$('#loginForm').submit() will submit the form.
Try this:
$(document).ready(function() {
function validateInput(id) {
var element = $("#"+id);
var success = false;
if (element.val() == null || element.val().trim() == "") {
element.closest("div").addClass("has-error");
} else {
var div = element .closest("div");
div.removeClass("has-error");
div.addClass("has-success");
success = true;
}
return success;
}
$(#loginButton).click(function() {
if (validateInput("usrName")) {
$('#loginForm').submit()
}
});
});
<div ng-class="{ 'form-group has-error has-feedback' : datos.campo.$invalid && !datos.campo.$pristine, 'form-group has-success has-feedback' : datos.campo.$valid}">
<label class="control-label" for="campo">Modelo</label>
<input ng-model="data.campo" name="campo" type="text" class="form-control" id="campo" required>
<span ng-class="{'glyphicon glyphicon-remove form-control-feedback':datos.campo.$invalid && !datos.campo.$pristine, 'glyphicon glyphicon-ok form-control-feedback':datos.campo.$valid}"></span>
<span ng-show="datos.campo.$invalid && !datos.campo.$pristine" class="col-md-8 center badge badge-danger">Incorrecto</span>
</div>
Con Angular JS es mas facil validar campos, Checa este link
This code will check EVERY input field.
$(#loginButton).click(function() {
if (!$.trim($("input").val()) { //check ALL input fields, see if they have valid (non-falsy) values
alert("some input needs fixin'!");
} else {
submit(); //since you mentioned this in your post
$.ajax({});//or make an ajax call, or put it inside of a function and call that, the possibilities are endless..
}
});
Although this can be done in several ways, using your example, I can see that you are already returning false on validation failure. Return true from the end of your validateInput() method.
function validateInput(item) {
var div=item.closest("div");
if(item.val()==null || item.val()=="") {
div.addClass("has-error");
return false;
} else {
div.removeClass("has-error");
div.addClass("has-success");
return true;
}
}
Then, in the click event handler, check the returned value and call the form.submit()
$('#loginButton').click(function() {
var isValid = true;
$('.form-control').each(function(){
isValid &= validateInput($(this));
});
if (isValid)
{
var data = $('#loginForm').serialize();
$.ajax({
url: 'your endpoint',
type: 'POST',
data: data
});
}
});
to submit the form.
Here's a working Plunkr.
You could use this plugin. This is the best and easiest to use plugin I have found for validating a form.

Contact form variables are not passing into javascript from section tag

Contact form variables are not passing into javascript. basically javascript fail on validation. On debug, I am getting "undefined is not a function." I have several seperators on this page. If i put identical code inside a seperate page like "contact.html" variables pass into javascript.
My understanding is that HTML tag id="contact-form" for some reason does not pass into the function.
Java Script
function code_contactvalidation() {
// Add form.special data (required for validation)
$('form.special input, form.special textarea').each(function() {
this.data = {};
this.data.self = $(this);
var val = this.data.self.val();
this.data.label = (val && val.length) ? val : null;
this.data.required = this.data.self.attr('aria-required') == 'true';
});
// Special form focus & blur
$('form.special input, form.special textarea').focus(function() {
with (this.data) {
console.log('focusing');
if ( label && self.val() == label) self.val('');
else return;
}
}).blur(function() {
with (this.data) {
if ( label && self.val().length == 0 ) self.val(label)
else return;
}
});
// initialize captcha
var randomcaptcha = function() {
var random_num1=Math.round((Math.random()*10));
var random_num2=Math.round((Math.random()*10));
document.getElementById('num1').innerHTML=random_num1;
document.getElementById('num2').innerHTML=random_num2;
var n3 = parseInt(random_num1) * parseInt(random_num2);
$('#captcharesult').attr('value', n3);
$('#buttonsubmit').attr('value','Submit');
};
randomcaptcha();
//initialize vars for contact form
var sending = false,
sent_message = false;
$('#contact-form').each(function() {
var _this = this;
this.data = {};
this.data.self = $(this);
this.data.fields = {};
this.data.labels = {};
this.data.notification = this.data.self.find('.notification');
_.each(['name','email','subject'], function(name) {
_this.data.fields[name] = _this.data.self.find(_.sprintf('input[name=%s]', name));
_this.data.labels[name] = _this.data.fields[name].val();
});
}).validate({
errorPlacement: function() {},
highlight: function(element) { $(element).addClass('invalid'); },
unhighlight: function(element) { $(element).removeClass('invalid'); },
submitHandler: function(form) {
if (sending) return false;
if ( sent_message ) { alert('Your message has been sent, Thanks!'); return false; }
var field, valid = true;
with (form.data) {
_.each(fields, function(field, name) {
if ( $.trim(field.val()) == labels[name] ) { valid = false; field.addClass('invalid'); } else { field.removeClass('invalid'); }
});
}
if (valid) {
sending = true;
$('#ajax-loader').show();
form.data.self.ajaxSubmit({
error: function(errorres) {
$('#ajax-loader').hide();
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
},
success: function(res) {
sending = false;
$('#ajax-loader').hide();
if (res == 'success') {
sent_message = true;
form.data.notification.removeClass('error').addClass('success').find('span:first-child').html('Your message has been sent!');
form.data.notification.animate({opacity: 100}).fadeIn(500);
$('#formName').val("");
$('#formEmail').val("");
$('#formSubject').val("");
$('#formMessage').val("");
$('#formcheck').val("");
} else if (res == 'captchaerror') {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Captcha Error');
form.data.notification.animate({opacity: 100}).fadeIn(500);
} else {
randomcaptcha();
form.data.notification.removeClass('sucess').addClass('error').find('span:first-child').html('Unable to send message (Unknown server error)');
form.data.notification.animate({opacity: 100}).fadeIn(500);
}
}
});
}
return false;
}
});
}
HTML
<section id="contact">
<div class="container">
<div class="row text-center">
<div id="principal" data-align="left">
<div class="form_group_contact">
<script type="text/javascript" src="js/jquery.validate.pack.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<form class="contactForm special validate" id="contact-form" action="sendmsg.php" method="post">
<p><input id="formName" name="name" type="text" value="Name" class="required" /></p>
<p><input id="formEmail" name="email" type="text" value="Email" class="required email" /></p>
<p><input id="formSubject" name="subject" class="last required" type="text" value="Subject" /></p>
<p><textarea id="formMessage" name="message" class="required margin20" rows="4" cols="83"></textarea></p>
<div class="form_captcha margin20">
<p>Captcha Recognition (<span id="num1"></span> * <span id="num2"></span>) =
<input type="hidden" id="captcharesult" name="captcha_result" value=""/>
<input type="text" class="required number" maxlength="3" size="3" id="formcheck" name="captcha" value=""/>
</p>
</div>
<p class="notification" style="display: none;"><span></span> <span class="close" data-action="dismiss"></span></p>
<p><input type="submit" value="" class="margin20" id="buttonsubmit" /><img id="ajax-loader" alt="" src="./images/ajax-loader.gif" /></p>
</form>
</div>
</div>
</div>
</div>
</section>
if ( label && self.val().length == 0 ) self.val(label)
There needs to be a semicolumn (;) to end that line ;)
Also, you call "each" on the contact-form which makes me think you expect more than one contact-form. You will need to set the identifier as "class" rather than "id" in the HTML and use "." in the jQuery selector rather than "#".
Now you got those little things fixed, please try it out in Firefox. Google is very vague with javascript errors, Firefox will give you a better error message. Please share it with us so I can edit this post with a final solution.

Debugging failing jQuery validate addMethod

I have a page where almost every click is handled by delegate().
http://itsneworleans.com/shows/midnight-menu-plus-1/blogs/after-midnight?preview=1
I set up jQuery validate like so
$(document).ready(function(){
$(".commentform form").validate({
rules: {
antispam: { equalToParam: "INO" }
}
});
jQuery.validator.addMethod("equalToParam", function(value, element, param) {
return value == param;
},
"Anti-spam field does not match requested value.");
});
if I check in console with
$.validator.methods['equalToParam']
I get back
function (value, element, param) { return value == param; }
so that looks good.
The validation works on the form submission BUT the equalToParam method has no effect. Only the "required" events occur for it.
The field HTML is
<input name="antispam" type="text" class="required" id="antispam" size="5" />
Where am I going wrong?
EDIT Here is whole form code (generated from PHP script and added to page via AJAX):
<? if ($post = (int) $_POST['pID']) { ?>
<div class="commentform">
<form>
<div class="commenttext">Comment:<br>
<textarea name="comment" class="required"></textarea>
</div>
<div class="commenttext">Your name:<br>
<input type="text" name="name" class="required">
</div>
<div class="commenttext">Your email (will not be publically visible):<br>
<input type="text" name="email" class="required email">
</div>
<div class="commenttext">Type the letters INO here to help us beat spam!<br>
<input name="antispam" type="text" class="required" id="antispam" size="5" />
</div>
<div class="commenttext">
<input type="button" name="submitcomment" class="submitcomment" value="Submit Comment">
<input type="hidden" name="post" value="<?=$post?>">
<? if ($parentComment = (int) $_POST['cID']) { ?>
<input type="hidden" name="parent" value="<?=$parentComment?>">
<? } ?>
</div>
</form>
</div>
<? } ?>
EDIT AGAIN And here's the click delegation code...
$("body").delegate(".submitcomment", "click", function(e) {
e.preventDefault();
var theform = $(this).closest("form");
console.log('Posting comment');
if ($(".commentform form").valid()) {
$.ajax({
type: "POST",
url: "/addComment.php",
data: theform.serialize()
}).done(function(html) {
if (html == 'OK') {
$(theform).html("<div class='commentposted'>Your comment has been received. Thank you. A moderator will review it for public viewing.</div>");
} else {
alert(html);
}
});
}
});
EDIT Here is the code which populates the form into the space where the Reply to Post link was:
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
});
When you need to apply the .validate() method to more than one form, you must wrap it within a jQuery .each().
$(".commentform form").each(function() {
$(this).validate({
rules: {
antispam: {
equalToParam: "INO"
}
}
});
});
EDIT:
You need to initialize the plugin AFTER the form is inserted into the page. Assuming this code properly inserts the form... put your .validate() call as the last item inside...
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
$(".commentform form").validate({ // <- initialize plugin AFTER form is inserted
// your rules & options
});
});
EDIT 2:
Include the equalToParam function someplace on your page within a DOM ready event handler.

Categories

Resources