I have form with jQuery validation defined as follows.
//#costCalculation is a form id
$('#costCalculation').validate({
onsubmit: false, //To prevent validation during form submit
errorClass: "my-error-class",
rules: {
adSizeFull: {
required: true
},
fullAdNo: {
required: true
}
},
messages: {
adSizeFull: "Please select Full adsize",
fullAdNo: "Please select total Ads(Full)"
},
submitHandler: function (form) { // for demo
//alert('valid form');
return true;
}
});
I have a form with select box like this
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label class="control-label col-xs-4">Ads(Full):</label>
<div class="col-xs-8">
<select name="adSizeFull" id="fullads-list" class="form-control" onchange="fullAdSizeChange()">
<option value="">--Select--</option>
</select>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label class="control-label col-xs-4" for="fullAdNo">#:</label>
<div class="col-xs-8">
<select name="fullAdNo" id="fulladnos-list" class="form-control" onchange="fullAdNoChange()">
<option value="">--Select--</option>
</select>
</div>
</div>
</div>
</div>
I would like to remove validation in the following scenario JS
function fullAdSizeChange() {
var adSizeFull = $("#fullads-list").val();
var fullAdNo = $("#fulladnos-list").val();
if(adSizeFull == "" && fullAdNo == "") {
$("#fullads-list").rules("remove", "required");
$("#fulladnos-list").rules("remove", "required");
}
}
How to remove the validation from specific elements if the form is specified as above??
I haven't copied the entire code. There may problems in syntaxes. I need guidelines only to implement this
jQuery Validate actually directly supports dependency expressions.
All you need to do is change your validate options like this:
parent: {
required: function(element) {
return $("#age").val() < 13;
// Makes "parent" required only if age is below 13.
}
Full Example:
$( "#myform" ).validate({
rules: {
age: {
required: true,
min: 3
},
parent: {
required: function(element) {
return $("#age").val() < 13;
}
}
}
});
}
just add the required class in both select box class no need to add change event
<select name="adSizeFull" id="fullads-list" class="form-control required" onchange="fullAdSizeChange()">
<option value="">--Select--</option>
</select>
Related
im new to jquery validator, im trying to use regex to check if numbers, capital and special characters are included. I have the following html
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row white-bg spacepad">
<div id="keypass">
<form method="POST" class="form-horizontal" id="keyform" name="keypasser">
<div class="form-group"><label class="col-sm-2 control-label">Decryption Key For EPins</label>
<div class="col-sm-10"><input type="text" required="required" class="form-control" name="keypassx" /></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Confirm Decryption Key</label>
<div class="col-sm-10"><input type="text" required="required" class="form-control" name="keypass2" /></div>
</div>
<input type="submit" class="btn btn-primary btn-rounded btn-block" value="Submit" />
</form>
</div>
</div>
and the following jquery, when i remove the addmethod it works, please what am i doing wrong
<script type="text/javascript">
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("form[name='keypasser']").validate({
// Specify validation rules
rules: {
keypassx: {
required: true,
minlength: 8,
passchecker: true,
},
keypass2: {
required: true,
equalTo: "#keypassx",
}
},
// Specify validation error messages
messages: {
keypassx: {
required: "Epins password required",
minlength: "Minimum length allowed is 8 characters",
passchecker: "Password should contain numbers, special characters and one uppercase",
},
keypass2: {
required: "Confirmation password requied",
equalTo: "Password does not match Epins Password",
}
},
$.validator.addMethod("passchecker",
function(value, element) {
return /^[A-Za-z0-9\d=!\-#._*]*$/.test(value);
});
// Make sure the form is submitted to the destination defined
// in the "action" attribute of the form when valid
submitHandler: function(form) {
form.submit();
}
});
});
</script>
kindly help out
Please try to use regular expression as
var patt = new RegExp("e");
var res = patt.test(str);
You directly use the regular expression. Please create object and try it.
The addMethod function accepts three params check the docs:
$.validator.addMethod("passchecker",
function(value, element) {
if(/^[A-Za-z0-9\d=!\-#._*]*$/.test(value)) {
return true;
} else {
return false;
}
}, "Your validation message goes here");
I have the following javascript:
var $step = $(".wizard-step:visible:last"); // get current step
var validator = $("#WizardForm").validate(); // obtain validator
var anyError = false;
$step.find("input").each(function ()
{
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
This is successfully validating all my input fields but upon trying to apply a similar method to the select type using code:
$step.find("select").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
My HTML is as follows:
<div class="wizard-step" id="step1" visibility="hidden" style="display: block;">
<div class="row">
<div class="col-md-6 column ui-sortable">
<div class="form-group">
<label class="control-label col-md-4" for="Tariff_Type">Tariff Type</label>
<div class="col-md-8">
<select style="width:100%;height:35px;border-radius:4px;padding-left:10px;" id="TariffType" name="TariffType" class="form-control input required">
<option value="">Please Select Tariff Type</option>
<option value="keypad account">Say Hello To Budget Extra Discount</option>
<option value="bill pay account">Standard 24H</option>
</select>
<span class="field-validation-valid text-danger" data-valmsg-for="TariffType" data-valmsg-replace="true"></span>
</div>
</div>
</div>
</div>
</div>
How can I ensure that a TariffType value is selected using this method?
Try the .valid() method instead...
if (! $(this).valid()) { ...
I'm working with a multi-step form. The fields are styled by bootstrap and the validations are done with jQuery. Right now only the text-fields are validating (like name, last name) but not: email, tel, any radio buttons or selectors etc. I need these forms to validate as well. But I also need this form to make an HTTP POST (probably with PHP, upon click of the next, and submit button which I will address in another question.
Here are a couple of my fields in html
<div class="form-bottom">
<div class="form-group">
<label for="sel2">choose an option (Choose One)</label>
<select class="form-control input-lg" id="sel2">
<option value="" disabled="" selected="" style="display: none;">Select One</option>
<option>First Option</option>
<option>An Option</option>
<option>Another Option</option>
</select>
</div>
<div class="form-group">
<label for="pwd">Email</label>
<input type="Email" class="form-control input-lg" id="pwd" placeholder="johndoe#gmail.com">
</div>
Below is the validating jQuery method:
$('.registration-form fieldset:first-child').fadeIn('slow');
$('.registration-form input[type="text"], .registration-form input[type="password"], .registration-form textarea').on('focus', function() {
$(this).removeClass('input-error');
});//.registration-form input[type="tel-lg"],
$('.registration-form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
parent_fieldset.find('input[type="text"], input[type="password"], textarea').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
if( next_step ) {
parent_fieldset.fadeOut(400, function() {
$(this).next().fadeIn();
});
}
});
I would think just adding something, at least the email field input[type="email"], to the top line would do this, but it does not.
Note: I wound up switching to the actual jQuery-validator pluggin. It was much easier to use, and I would suggest it for anyone focusing on front-end Validations.
http://jqueryvalidation.org/documentation/
EX:
$('.form3').validate({ // initialize plugin
// ignore:":not(:visible)",
rules: {
Surgery_Year: {
required: true,
number: true,
},
Has_Surgery: {
required: true,
number: false,
},
Has_Rev_Surgery: {
required: true,
number: false,
},
Rev_Surgery_Year: {
required: true,
number: true,
},
}
I'm facing some problems with jQuery Validate. I've already put the rules but when i'm submitting the form, nothing happens.
I'm using ASP.NET MVC 4 and Visual Studio 2010.
EDIT: Click here to see my entire code. I'm trying to post it here but i'm getting the following error: 403 Forbidden: IPS signature match. Below is part of my code with Andrei Dvoynos's suggestion. I'm getting the same error. Clicking on submit and the page being reloaded
#{
ViewBag.Title = "Index";
}
#section Teste1{
<script type="text/javascript">
$(document).ready(function () {
$("#moeda").maskMoney();
$("#percent").maskMoney();
$(":input").inputmask();
$('#tel').focusout(function () {
var phone, element;
element = $(this);
element.unmask();
phone = element.val().replace(/\D/g, '');
if (phone.length > 10) {
element.inputmask({ "mask": "(99) 99999-999[9]" });
} else {
element.inputmask({ "mask": "(99) 9999-9999[9]" });
}
}).trigger('focusout');
//the code suggested by Andrei Dvoynos, i've tried but it's occurring the same.
$("#form1").validate({
rules: {
cpf: { required: true, },
cep: { required: true, },
tel: { required: true, },
email: { required: true, },
cnpj: { required: true, },
},
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'
});
});
</script>
}
#using (#Html.BeginForm("", "", FormMethod.Post,
new { id = "form1", name = "form1" }))
{
<fieldset>
<legend>Sign In</legend>
<div class="form-group" id="divCpf">
<label for="cpf">CPF</label>
<input data-inputmask="'mask': '999.999.999-99'" class="form-control" id="cpf" />
</div>
<div class="form-group" id="divCep">
<label for="cep">CEP</label>
<input data-inputmask="'mask' : '99999-999'" type="text" class="form-control" id="cep" placeholder="CEP" />
</div>
<div class="form-group" id="divTel">
<label for="tel">Telefone</label>
<input type="text" class="form-control" id="tel" placeholder="tel" />
</div>
<div class="form-group" id="email">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" placeholder="Email" />
</div>
<div class="form-group" id="divcnpj">
<label for="cnpj">CNPJ</label>
<input data-inputmask="'mask' : '99.999.999/9999-99'" type="text" class="form-control" id="cnpj" placeholder="CNPJ" />
</div>
<div class="form-group">
<label for="moeda">Moeda</label>
<input type="text" id="moeda" data-allow-zero="true" class="form-control" />
</div>
<div class="form-group">
<label for="Percent">Percent</label>
<input type="text" id="percent" data-suffix="%" data-allow-zero="true" class="form-control" maxlength="7" />
</div>
<input type="submit" class="btn btn-default" value="Sign In" id="sign" />
</fieldset>
}
My tests (all unsuccessful):
1 - put the $("form").validate() into $(document).ready()
2 - put the required class on the fields.
jQuery Validate plugin version: 1.13.0
In addition to the fatal problem you fixed thanks to #Andrei, you also have one more fatal flaw. The name attribute is missing from your inputs.
Every element must contain a unique name attribute. This is a requirement of the plugin because it's how it keeps track of every input.
The name is the target for declaring rules inside of the rules option.
$("#form1").validate({
rules: { // <- all rule declarations must be contained within 'rules' option
cpf: { // <- this is the NAME attribute
required: true,
....
DEMO: http://jsfiddle.net/3tLzh/
You're missing the rules property when calling the validate function, try something like this:
$("#form1").validate({
rules: {
cpf: { required: true, },
cep: { required: true, },
tel: { required: true, },
email: { required: true, },
cnpj: { required: true, },
},
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'
});
i design show/hide div select box using select2 and validate using jquery validation plugin. this worked but when i select empty value(select a color) validation show success (green color) but if i click submit button i see red color.
JS:
$(document).ready(function () {
$(".lstColors").change(function () {
$('div.box').hide();
$('div.box.' + $(this).val()).show();
}).change();
$('form').validate({
rules: {
firstname: {
minlength: 3,
maxlength: 15,
required: true
},
lastname: {
minlength: 3,
maxlength: 15,
required: true
}
},
highlight: function (element, errorClass, validClass) {
if (element.type === "radio") {
this.findByName(element.name).addClass(errorClass).removeClass(validClass);
} else {
$(element).closest('.form-group').removeClass('has-success has-feedback').addClass('has-error has-feedback');
$(element).closest('.form-group').find('i.fa').remove();
$(element).closest('.form-group').append('<i class="fa icon-plane icon-2x form-control-feedback"></i>')
}
},
unhighlight: function (element, errorClass, validClass) {
if (element.type === "radio") {
this.findByName(element.name).removeClass(errorClass).addClass(validClass);
} else {
$(element).closest('.form-group').removeClass('has-error has-feedback').addClass('has-success has-feedback');
$(element).closest('.form-group').find('i.fa').remove();
$(element).closest('.form-group').append('<i class="fa icon-plane icon-2x form-control-feedback"></i>');
}
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function (error, element) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$('form').on('submit', function () {
$(this).addClass('submitted');
});
$("#lstColors").select2({
placeholder: "Select a Color",
triggerChange: true,
allowClear: true,
width: "200px"
}).on('change', function () {
if ($('form').hasClass('submitted')) $('form').valid();
});
});
HTML:
<form>
<div class="form-group">
<label class="control-label" for="firstname">Nome:</label>
<div class="col-md-6">
<div class="row">
<div class="col-md-3">
<div class="input-group select2-bootstrap-prepend"> <span class="input-group-addon"><i class=" icon-male"></i></span>
<input class="form-control" placeholder="Insira o seu nome prĂ³prio" name="firstname" type="text" />
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="lstColors" class="control-label">Favorite Colors:</label>
<div class="col-md-6">
<div class="row">
<div class="col-md-3">
<div class="input-group select2-bootstrap-prepend">
<select id="lstColors" class="lstColors required">
<option value=""></option>
<option value="red" selected>Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
<div class="red box">test</div>
<div class="green box">You have selected <strong>green option</strong> so i am here</div>
<div class="blue box">You have selected <strong>blue option</strong> so i am here</div>
</div>
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Now, i need to show red color after choose empty value(on change). how do can fix this ?
JSFIDDLE
Add new validation method right after the ready function
$.validator.addMethod("valueNotEquals", function(t, n, r) {
return t != r
}, $.validator.format("Invalid val is supplied."));
Validation rules should look like
rules: {
firstname: {
minlength: 3,
maxlength: 15,
required: true
},
lastname: {
minlength: 3,
maxlength: 15,
required: true
},
mySelect: {
valueNotEquals: 0
}
},
And of course do not forget to add name attribute to your select like in the rules declared above + placeholder option's value should be the value provided in rules (in this case 0)
<select id="lstColors" name="mySelect" class="lstColors required">
<option value="0"></option>
UPDATE
I noticed that if the value of placeholder option is changed the placeholder disappears, so I searched for another solution and found one:
$(".lstColors").on('select2-removed', function () {
if ($('form').hasClass('submitted')) $('form').valid();
});
Checkout the fiddle