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
Related
I am having trouble validating if input fields contains only whitespaces. I have specified the required rule for the required fields but it still works if I just type spaces. also, noSpace rule for username field does not seem to work. It disables validation for the other fields. Here is my markup.
<form method=post class="form-auth-small" action="../php/controller/registration_controller.php">
<div class="form-group row m-t-10px">
<div class="col-sm-6 text-left m-b-5px">
<label><h5>RANK: </h5></label>
<select class="form-control" name="rank" required="required">
<option value="rank1">NUP</option>
<option value="rank2">PO1</option>
<option value="rank3">PO2</option>
<option value="rank4">PO3</option>
<option value="rank5">SPO1</option>
<option value="rank6">SPO2</option>
<option value="rank7">SPO3</option>
<option value="rank8">SPO4</option>
<option value="rank9">PINSP</option>
<option value="rank10">PSINSP</option>
<option value="rank11">PCINSP</option>
<option value="rank12">PSUPT</option>
<option value="rank13">PSSUPT</option>
<option value="rank14">PCSUPT</option>
<option value="rank15">PDIR</option>
<option value="rank16">PDDG</option>
<option value="rank17">PDG</option>
</select>
</div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>USERNAME: </h5></label>
<input class="form-control" name="username" placeholder="Username must only contain characters [A-Z] and numbers [0-9]" type="text" minlength="1" required="required">
</div>
<div class="clearfix"></div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>FIRST NAME: </h5></label>
<input class="form-control" name="fname" type="text" minlength="1" required="required">
</div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>PASSWORD: </h5></label>
<input class="form-control" name="pwd" placeholder="Choose a strong password" type="password" minlength="1" required="required">
</div>
<div class="clearfix"></div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>MIDDLE NAME: </h5></label>
<input class="form-control" name="mname" type="text" minlength="1" required="required">
</div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>EMAIL: </h5></label>
<input class="form-control" name="email" type="email" minlength="1" required="required">
</div>
<div class="clearfix"></div>
<div class="col-sm-6 text-left m-b-5px">
<label><h5>LAST NAME: </h5></label>
<input class="form-control" name="lname" type="text" minlength="1" required="required">
</div>
</div>
<div class="form-group clearfix m-b-5px">
<button type="submit" name="btnRegister" class="btn btn-primary btn-lg btn-block">REGISTER</button>
</div>
<div class="bottom m-b-15px">
<span><i class="fa fa-lock"></i> Already have an account? Sign in.</span>
</div>
</form>
JS (Without noSpace rule)
$(document).ready(function () {
$('.form-auth-small').validate({
rules: {
rank: {
required: true
},
username: {
required: true,
minlength: 3
},
fname: {
required: true
},
mname: {
required: true
},
lname: {
required: true
},
pwd: {
required: true
},
email: {
required: true
}
},
errorElement: "em",
errorPlacement: function ( error, element ) {
// Add the `help-block` class to the error element
error.addClass( "help-block" );
// Add `has-feedback` class to the parent div.form-group
// in order to add icons to inputs
element.parents( ".col-sm-5" ).addClass( "has-feedback" );
error.insertAfter( element );
// Add the span element, if doesn't exists, and apply the icon classes to it.
if ( !element.next( "span" )[ 0 ] ) {
$( "<span class='glyphicon glyphicon-remove form-control-feedback'></span>" ).insertAfter( element );
}
},
success: function ( label, element ) {
// Add the span element, if doesn't exists, and apply the icon classes to it.
if ( !$( element ).next( "span" )[ 0 ] ) {
$( "<span class='glyphicon glyphicon-ok form-control-feedback'></span>" ).insertAfter( $( element ) );
}
},
highlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-sm-6" ).addClass( "has-error" ).removeClass( "has-success" );
$( element ).next( "span" ).addClass( "glyphicon-remove" ).removeClass( "glyphicon-ok" );
},
unhighlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-sm-6" ).addClass( "has-success" ).removeClass( "has-error" );
$( element ).next( "span" ).addClass( "glyphicon-ok" ).removeClass( "glyphicon-remove" );
}
});
});
DEMO
Thank you in advance!
Just add this method before your jQuery validate function run::
jQuery.validator.addMethod("noSpace", function(value, element) {
return value.indexOf(" ") < 0 && value != "";
}, "No space please and don't leave it empty");
AND use
noSpace: true
for each field you want.
Try this
$(document).ready(function() {
jQuery.validator.addMethod("noSpace", function(value, element) {
return value.indexOf(" ") < 0 && value != "";
}, "No space");
$(".form-auth-small").validate({
rules: {
username : {
noSpace: true
}
}
});
})
$(".form-auth-small").validate({
rules: {
username : {
required: true,
normalizer: function(value) {
return $.trim(value);
}
}
}
});
use normalizer , in which it will trim or remove all whitespaces.
simple solution.enjoy your day
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>
I use jquery validation plugin to do validation in a bootstrap modal form, when i send the form ,the jquery validation plugin is working but ajax code will do two time and the form cannot send out.
bootstrap form
<form class="contact">
<fieldset>
<div class="modal-body">
<ul class="nav nav-list">
<div class="form-group">
<label for="topic" class="control-label ">topic</label>
<input class="form-control" type="text" name="topic" />
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="ruser" class="control-label "> ruser: </label>
<input class="form-control" type="text" name="ruser" value="<?php echo $username; ?>" readonly/>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="content" class="control-label ">content:</label>
<textarea class="form-control" name="content" rows="3"></textarea>
<span class="help-block"></span>
</div>
</ul>
</div>
</fieldset>
<button class="btn btn-success" id="submitcontact">ok</button>
</form>
javascript
$(document).ready(function () {
$('form').validate({
rules: {
topic: {
required: true
},
ruser: {
required: true
},
content: {
required: true
}
},
messages: {
topic: {
required: 'enter topic'
},
ruser: {
required: 'enter nuser'
},
content: {
required: 'enter content'
}
},
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) {
if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "process.php",
data: $('form.contact').serialize(),
success: function (msg) {
alert("ok!");
if (msg == 'ok') {
alert(msg);
location.reload()
}
},
error: function () {
alert("failure");
}
});
return false;
}
});
$('#submitcontact').click(function () {
$('form.contact').submit();
})
});
How can i fix the problem?
The jsfiddle
You probably need to remove this bit:
$('#submitcontact').click(function(){
$('form.contact').submit();
})
Please see the example:
http://jsfiddle.net/8eoreedb/1/
Use .valid() method:
Description: Checks whether the selected form is valid or whether all selected elements are valid.
Updated Fiddle
$('#submitcontact').on('click', function() {
if ($('form.contact').valid()) {
// Form is valid
$('form.contact').submit();
}
});
Doc: http://jqueryvalidation.org/valid/
Demo: http://jsfiddle.net/8eoreedb/4/
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 work with jquery validation plugin for validate my form. in my form I have jquery upload file using jquery form plugin.
JS:
$(document).ready(function()
{
$("#fileuploader").uploadFile({
url: "upload.php",
dragDrop:true,
multiple:false,
fileName: "myfile",
returnType:"json",
showDelete:true,
showFileCounter:false,
onSuccess:function(fileArray, data, xhr, pd)
{
var url = "download.php?filename="+data[0];
//pd.filename.html(data[0]);
pd.filename.html("<a href='"+url+"'>"+data[0]+"</a>");
},
deleteCallback: function(data,pd)
{
for(var i=0;i<data.length;i++)
{
$.post("delete.php",{op:"delete",name:data[i]},
function(resp, textStatus, jqXHR)
{
//Show Message
alert("File Deleted");
});
}
pd.statusbar.hide(); //You choice to hide/not.
}
});
});
$('form').validate({
ignore:'.uploadFile',
rules: {
firstname: {
minlength: 3,
maxlength: 15,
required: true
},
lastname: {
minlength: 3,
maxlength: 15,
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',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
HTML:
<form>
<div id="fileuploader">Upload</div>
<div class="form-group">
<label class="control-label" for="firstname">Nome:</label>
<div class="input-group">
<span class="input-group-addon">$</span>
<input class="form-control" placeholder="Insira o seu nome próprio" name="firstname" type="text" />
</div>
</div>
<div class="form-group">
<label class="control-label" for="lastname">Apelido:</label>
<div class="input-group">
<span class="input-group-addon">€</span>
<input class="form-control" placeholder="Insira o seu apelido" name="lastname" type="text" />
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Now, jquery validation is a conflict with jquery form plugin and not validate my form. I tried ignore:'.uploadFile' function but jquery validation not work.
How can I fix this problem?!
Not Work DEMO : http://jsfiddle.net/hTPY7/1400/
Worked Demo without upload plugin: http://jsfiddle.net/hTPY7/1404/