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"/>
Related
I have several text inputs with the same name and I'm trying to prevent the form from submitting if the collective value of all the inputs is less than 1. E.g. the user can't put 0 on all of them, but must at least put 1 on one of them so the collective value of all inputs is at least 1.
I have created a method in jquery validate to check if the value is greater than 0 of the selected inputs
<td><input class='{nbTeams: true} nbTeamsVal' type="text" class="form-control" id="nbTeamsMiniSoccer_20" name="nbTeams[]"></td>
<td><input class='{nbTeams: true} nbTeamsVal' type="text" class="form-control" id="nbTeamsYouthMale_20" name="nbTeams[]"></td>
This is the method:
$.validator.addMethod("nbTeams", function(value, elem, param) {
return $(".nbTeamsVal").value > 0;
},"Collective value must be more than 1!"
);
This is my rule and custom message
$(document).ready(function () {
$('#myForm').validate({
rules: {
"nbTeams[]":{
required: true
}
},
messages: {
"nbTeams[]":"This group of fields can only contain numbers and one must contain a value of at least 1."
},
errorElement : 'div',
errorLabelContainer: '.errorTxt',
submitHandler: function (form) {
form.submit();
}
});
});
i edit your code try this :
$.validator.addMethod("nbTeams", function(value, elem) {
var sumOfVals = 0;
$(".nbTeamsVal").each(function () {
sumOfVals = sumOfVals + parseInt($(this).val());
});
return sumOfVals>0;
},"Collective value must be more than 1!"
);
$('#myForm').validate({
rules: {
"nbTeams[]":"nbTeams"
},
errorElement : 'div',
errorLabelContainer: '.errorTxt',
submitHandler: function (form) {
alert('valid form submitted'); // for demo
return false; // for demo
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<form id="myForm" method="post" action="#">
<td><input class='{nbTeams: true} nbTeamsVal' type="text" class="form-control" id="nbTeamsMiniSoccer_20" name="nbTeams[]" value="0"></td>
<td><input class='{nbTeams: true} nbTeamsVal' type="text" class="form-control" id="nbTeamsYouthMale_20" name="nbTeams[]" value="0"></td>
<div class="errorTxt"></div>
<button type="submit">Submit</button>
</form>
I am using the jquery-validation plugin to validate a simple form. It's working great.
Is it possible to restrict the keys from being typed in the textbox completely.
I got this FIDDLE which is somewhat close to what I want.
<form id="myform" method="post" action="">
<input type="text" id="cstName" name="cstName" />
<input type="text" id="cntNumber" name="cntNumber" />
<input type="submit" id="btn" name="btnSubmit" value="Submit" />
</form>
$.validator.addMethod(
"regex",
function (value, element, regexp) {
var re = new RegExp(regexp);
return this.optional(element) || re.test(element);
},
"Please check your input."
);
$(document).ready(function () {
$("#myform").validate({
rules: {
cstName: {
required: true, regex: /^[0-9\.\-\/]+$/
},
cntNumber: {
required: true
}
}
});
});
Here is a simple form created in my MYFIDDLE.
Can the words be restricted from being typed using the jquery-validate plugin. And while it restricts, can the error message still be shown??
If you want to disable entering 'invalid' characters entirely, you should add an on key press event listener which returns false when somebody enters a char which does not match your regex. Example:
$('input[name=cntNumber]').on('keypress', function(e) {
return String.fromCharCode(e.which).match(/[0-9\.\-\/]/) !== null;
});
I have a form that I am trying to validate that has two fields:
<div class="entryForm">
<div class="formField">
<label for="fieldEmailAddress">Email address:</label>
<input type="email" name="fieldEmailAddress" id="fieldEmailAddress"/>
</div>
<div class="formField">
<label for="fieldMobileNumber">Mobile number:</label>
<input type="text" name="fieldMobileNumber" id="fieldMobileNumber"/>
</div>
</div>
Here's my jQuery Validation wireup:
<script type="text/javascript">
$(document).ready(function () {
$('#form1').validate({ rules: { fieldMobileNumber: { phoneUS: true } } });
});
</script>
What I'd like to do is add an additional validation rule that says: the form is not valid if both fieldEmailAddress and fieldMobileNumber are blank. In other words, I'd like to make it such that at least one of either fieldEmailAddress or fieldMobileNumber is required. It seems like most of the jQuery Validation custom methods are designed to only work for one field at a time - I need to validate both.
Any ideas?
You can bypass the Validate plugin and do a check like the following:
$("#form1").submit(function() {
var email = $('#fieldEmailAddress');
var phone = $('#fieldMobileNumber');
if(email.val() == '' && phone.val() == '') {
alert('Fill out both fields');
}
else if(email.val() == '') {
alert('Email, please...');
}
else if(phone.val() == '') {
alert('Phone, please...');
}
else {
alert('Yay!');
}
});
You simply need to include the additional-methods.js file and use the require_from_group method.
require_from_group: [x, '.class']
// x = number of items required from a group of items.
// .class = class assigned to every form element included in the group.
jQuery:
$(document).ready(function () {
$('#form1').validate({
rules: {
fieldMobileNumber: {
phoneUS: true,
require_from_group: [1, '.mygroup']
},
fieldEmailAddress: {
require_from_group: [1, '.mygroup']
}
},
groups: {
theGroup: 'fieldMobileNumber fieldEmailAddress'
}
});
});
Add class="mygroup" to each input you need to group together...
<input type="email" name="fieldEmailAddress" id="fieldEmailAddress" class="mygroup" />
And finally, optionally use the groups option to lump the messages into one...
groups: {
theGroup: 'fieldMobileNumber fieldEmailAddress'
}
Working DEMO: http://jsfiddle.net/CYZZy/
If you don't like where the validation message is placed, that's where you'd tweak it using the errorPlacement callback function.
I'm trying to implement validation into my form being conditional. Basically if the user selects email radio option then email is going to be required, or if phone is selected then phone field would be required.
So far I've gotten this code to work, form submits and validation works fine. But if I switch to phone, then switch back to email, the validation is loaded so form won't submit if I haven't filled out both fields.
I have it set that way but basically trying to make it so if one field is selected then the other required. Any better ways to do this?
HTML:
<label>Method of Contact</label>
<label class="radio">
<input type="radio" name="group" value="ck1" checked/>
Email
</label><br />
<label class="radio"><input type="radio" name="group" value="ck2" />
Phone
</label>
<div id="emaildisp">
<label>Email</label>
<input id="emailv" name="email" type="email" />
</div>
<div id="phonedisp">
<label>Phone</label>
<input id="phonev" name="phone" type="text" />
</div>
Javascript:
$(function()
{
if (jQuery('input[value=ck2]:checked').length > 0)
{
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#phonev").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
}
else
{
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#emailv").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
jQuery('input[name=group]').change(function()
{
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2')
{
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#phonev").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
}
else
{
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#emailv").validate(
{
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
});
});
Solution:
Thanks to the answers below, I came up with the solution. Key difference, I was not using jquery validation plugin, rather a different validation script. So I switched over, for beginners, just look it up you'll simply have to add link to the script in the header.
Next I gave the form an id, #myform. Then I have the ck1 and ck2 radio button their own respective ids, #ck1id and #ck2id. And using the below code, if the radio button is selected, then depending on the id selected, next part becomes validation required.
<script type='text/javascript'>
$(function(){
jQuery('input[name=group]').change(function() {
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2'){
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
} else {
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
}
});
jQuery('input[name=group]').triggerHandler('change');
});
</script>
<script>
$(function(){
// validate signup form on keyup and submit
$("#myform").validate({
rules: {
group: "required",
email:
{
required: '#ck1id:checked',
email: true
},
phone:
{
required: '#ck2id:checked',
digits: true
}
},
messages: {
group: "Please select one",
email: "Please enter your email.",
phone: "Please enter your phone."
}
});
});
</script>
You need to remove the previously added validation from the other fields those are not required. If you need phone remove validation from email and vice versa.
You can follow two way, either remove validation or ignore the validation.
1. Removing the validation:
jQuery("#emailv").rules('remove');
or
jQuery("#phonev").rules('remove');
2. Ignore validation:
jQuery("#emailv").validate({
ignore: "#emailv"
});
or
jQuery("#phonev").validate({
ignore: "#phonev"
});
Check if this helps you.
Use .rules("remove") to remove jquery validation.
$(function(){
jQuery('input[name=group]').change(function() {
var selected = jQuery(this).val();console.log(selected);
if(selected == 'ck2'){
jQuery('#phonedisp').show();
jQuery('#emaildisp').hide();
jQuery("#emailv").rules("remove"); //remove the other field validation
jQuery("#phonev").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter your phone number"
});
} else {
jQuery('#phonedisp').hide();
jQuery('#emaildisp').show();
jQuery("#phonev").rules("remove"); //remove the other field validation
jQuery("#emailv").validate({
expression: "if (VAL) return true; else return false;",
message: "Please enter your email"
});
}
});
jQuery('input[name=group]').triggerHandler("change");
});
I see that you have duplicated code, just remove it and use jQuery('input[name=group]').triggerHandler("change"); to trigger it when page first loads
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>