I have two radio buttons and a text input. I want one of the radios required for the text input to be then validated. I can disable the text input field unless selected, but I think it would be more user intuitive to allow text input first, and only error if they don't also select a radio.
The form is giving me back an error that the radios are required, but I don't want the remote check to kick in unless one of the radio buttons is selected.
So here's what I have...
JQuery:
jQuery( "#modalform" ).validate({
onkeyup: false,
onfocusout: false,
rules: {
'register_domain[]': {
required: true
},
chosen_domain: {
required: true,
minlength: 4,
remote: {
url: "check.php",
type: "post",
data: {
register_domain: function() {
return jQuery('input[name="register_domain[]"]');
}
}
}
}
},
messages: {
'register_domain[]': {
required: "Choose one"
},
chosen_domain: {
required: "Required input",
minlength: jQuery.validator.format("Please, at least {0} characters are necessary"),
remote: jQuery.validator.format("Invalid domain name: {0}")
}
}
});
Form Fields:
<label class="radio-inline">
<input type="radio" name="register_domain[]" id="own_domain" value="owned"> Own Domain
</label>
<label class="radio-inline">
<input type="radio" name="register_domain[]" id="new_domain" value="new"> Register Domain
</label>
<label for="register_domain[]" class="error" style="display:none;">Please choose one.</label>
<input type="text" size="50" placeholder="www." id="inputDomain" name="chosen_domain" class="form-control required" required="required">
Quote OP:
"I don't want the remote check to kick in unless one of the radio buttons is selected."
You can use the rules('add') and rules('remove') methods to toggle the remote rule within an external change handler...
$('input[name="register_domain[]"]').on('change', function() {
if ($(this).val() == "owned") {
$('input[name="chosen_domain"]').rules('remove', 'remote');
} else {
$('input[name="chosen_domain"]').rules('add', {
remote: {
url: "check.php",
type: "post",
data: {
register_domain: function() {
return jQuery('input[name="register_domain[]"]');
}
}
}
});
}
});
Related
I've well researched and used this, but I don't know it is still getting error.
I need to check if existing image exists then file attribute should skip validation and viceversa.
HTML COde:
<input type="file" name="image" id="image">
<input type="hidden" name="old_image" value="">
JQuery Validation Code:
$("#add_reference").validate({
rules: {
link: {
required: true,
},
image:{
//required: true,
required: function(element) {
if ($("#old_image").val() == '')
{
return true;
}
else
{
return false;
}
},
accept:"jpg,png,jpeg,gif"
},
},
messages: {
link: {
required: "Please enter link title",
},
image:{
required: "Please choose image",
accept: "Please choose valid image files",
},
},
errorPlacement: function (error, element) {
var attr_name = element.attr('name');
error.insertAfter(element);
}
});
Can Anyone tell me where I am going wrong?
There is no id in your input tag,instead you should add id attribute.
<input type="hidden" name="old_image" id="old_image" value="">
and you are calling it by id
if ($("#old_image").val() == '')
<input type="file" name="image" id="image">
<input type="hidden" id="old_image" name="old_image" value="">
Your validation won't fire because it is always passing the test, you are testing if #old_image is empty and as you can see it is always empty, are you triggering an event after you upload your file???
You can do it with this event..
$(function() {
$("input:file").change(function (){
var fileName = $(this).val();
$("#old_image").val(fileName);
});
});
I am attempting to add validation for a non-input, custom selection. I have a series of images that the user clicks, which act as a checkbox, but do not actually have an input. I am using jQuery validate for the rest of my form and wanted to see if there was anyway that I can add validation, whether it is adding a method (I read jQuery validate only works on inputs) or something else that will work with one click of submit.
I am wanting something similar to this, but to work like jQuery validate.
if(checkValue.length < 1) {
alert("You need at least one interested selected.");
}
I tried putting the above if-statement above the rules section in the validation code, but it throws an error.
Does anyone have any alternative ideas that I could try?
//Getting Value of the interest boxes
var interest = $('.interest');
var checkVal = '';
var checkValue = '';
interest.click(function() {
checkVal = [];
$(this).toggleClass('active');
$('.interestBox', this).toggleClass('active');
interest.each(function() {
if($(this).is('.active')) {
checkVal.push($(this).data('title'));
}
});
checkValue = checkVal.join(', ');
console.log(checkValue);
});
//Jquery Validate
$('#salesforce_submit').validate({
rules: {
first_name: {
required: true,
minlength: 2
}
},
messages: {
first_name: {
required: "Please enter your first name",
minlength: "Your first name seems a bit short, doesn't it?"
}
},
submitHandler: function(form) {
event.preventDefault();
var datastring = $('#salesforce_submit').serialize();
$.ajax({
url: '/php/quoteSend.php',
type: 'POST',
data: datastring
,
success: function(data) {
if (data == 'Error!') {
alert(data);
} else {
}
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
console.log('error');
}
});
}
});
.interest img {
height: 50px;
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form id="salesforce_submit" type="Post">
<div><input id="first_name" placeholder="First Name*" class="input block" maxlength="40" name="first_name" type="text"></div>
<h3 class="interestTitle">A</h3>
<div class="interest" data-title="A">
<img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="A">
</div>
<h3 class="interestTitle">B</h3>
<div class="interest" data-title="B">
<img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="B">
</div>
<h3 class="interestTitle">C</h3>
<div class="interest" data-title="C">
<img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="C">
</div>
<input type="Submit" value="Submit">
Full code:
<section class="sec90">
<h3 class="subTC">Enter your information below.</h3>
<form action="" id="salesforce_submit" method="POST" enctype="multipart/form-data">
<input name="oid" type="hidden" value=""><input type="hidden" id="" id="interestValue" multiple="multiple" name="" value=""><input name="retURL" type="hidden"> <input name="lead_source" required="" type="hidden" value="Quote Form"> <input id="txt_medium" name="txt_medium" type="hidden" value=""> <input id="txt_source" name="txt_source" type="hidden" value=""> <input id="txt_campaign_name" name="txt_campaign_name" type="hidden" value=""> <input id="txt_term" name="txt_term" type="hidden" value=""> <input id="txt_content" name="txt_content" type="hidden" value="">
<div><input id="first_name" placeholder="First Name*" class="input block" maxlength="40" name="first_name" type="text"></div>
<div><input id="last_name" placeholder="Last Name*" class="input block" maxlength="80" name="last_name" type="text"></div>
<div><input id="email" placeholder="Email*" class="input block" maxlength="80" name="email" type="email"></div>
<div><input id="phone" placeholder="Phone* no dashes" class="input block" maxlength="12" name="phone" type="tel"></div>
<div><input id="zip" placeholder="Zip/Postal Code*" class="input block" maxlength="5" name="zip" type="text" pattern= "[0-9]{5}"></div>
<div><input id="company" placeholder="Company*" class="input block" maxlength="40" name="company" type="text"></div>
</section>
<section class="sec90">
<h3 class="subTC">What are you interested in?*</h3>
<div><input type="hidden" name="interestHidden" value=""></div>
<section class="sec90" id="up">
<h3 class="subTC">Describe your project*</h3>
<div><textarea id="description" name="description" placeholder="Provide as much detail as possible"></textarea></div>
<h3 class="subTC block">Have a .stp file or drawing example? Send it for quicker quote times.</h3>
<input type="file" name="uploadedFile" class="inputfile" id="uploadedFile" data-multiple-caption="{count} files selected" multiple>
<label for="uploadedFile" class="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" viewBox="0 0 20 17"><path d="M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z"/></svg><span class="marL5">Upload file</span></label>
<input type="hidden" name="MAX_FILE_SIZE" value="10000000">
<div class="margBot40"></div>
</section>
<input name="submit" class="block testB" type="submit" value="SUBMIT QUOTE">
</form>
JS:
var interest = $('.interest');
var checkVal = '';
var checkValue = '';
var showMe = '';
interest.click(function() {
checkVal = [];
$(this).toggleClass('active');
$('.interestBox', this).toggleClass('active');
interest.each(function() {
if($(this).is('.active')) {
checkVal.push($(this).data('title'));
}
});
checkValue = checkVal.join(', ');
console.log(checkValue);
//Hidden interest input value
var checkLength = checkVal.length;
console.log(checkLength);
$('[name="interestHidden"]').val(checkLength);
var interestVal = $('interestValue').val()
interestVal = checkValue;
showMe = interestVal;
console.log('Hidden val is ' + showMe);
});
/*$('#phone').keyup(function() {
$(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'));
});*/
$('#phone').keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$text = $(this);
if (key !== 8 && key !== 9) {
if ($text.val().length === 3) {
$text.val($text.val() + '-');
}
if ($text.val().length === 7) {
$text.val($text.val() + '-');
}
}
return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});
var inputs = document.querySelectorAll( '.inputfile' );
Array.prototype.forEach.call( inputs, function( input )
{
var label = input.nextElementSibling,
labelVal = label.innerHTML;
input.addEventListener( 'change', function( e )
{
var fileName = '';
if( this.files && this.files.length > 1 )
fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
else
fileName = e.target.value.split( '\\' ).pop();
if( fileName )
label.querySelector( 'span' ).innerHTML = fileName;
else
label.innerHTML = labelVal;
});
});
$('#phone').keyup(function() {
jQuery.validator.addMethod("alphanumeric", function(value, element) {
//return this.optional(element) || /^[a-z0-9\-]+$/i.test(value);
return this.optional(element) || /^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/i.test(value);
}, "Numbers and dashes only");
});
$('#salesforce_submit').validate({
ignore: [],
rules: {
first_name: {
required: true,
minlength: 2
},
last_name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
phone: {
required: true,
//digits: true,
minlength: 10,
alphanumeric: true
},
zip: {
required: true,
digits: true,
minlength: 5
},
company: {
required: true,
minlength: 2
},
interestHidden: {
required: true,
min: 1
}/*,
description: {
required: true,
minlength: 5
}*/
},
messages: {
first_name: {
required: "Please enter your first name",
minlength: "Your first name seems a bit short, doesn't it?"
},
last_name: {
required: "Please enter your last name",
minlength: "Your last name seems a bit short, doesn't it?"
},
email: {
required: "Please enter your email address",
email: "Please enter a valid email address"
},
phone: {
required: "Please enter your phone number",
digits: "Please enter a valid phone number with only numbers",
minlength: "Your number seems a bit short, doesn't it?"
},
zip: {
required: "Please enter your zip code",
digits: "Please enter a valid zip code with only numbers",
minlength: "Your zip code seems a bit short, doesn't it?"
},
company: {
required: "Please enter your company name",
minlength: "Your company name seems a bit short. Please enter at least 2 characters"
},
interestHidden: {
required: "Please choose at least one interest",
min: "At least one interest needs chosen"
}/*,
description: {
required: "Please enter your project description",
minlength: "Your description seems a bit short, doesn't it?"
}*/
},
submitHandler: function(form) {
event.preventDefault();
var datastring = $('#salesforce_submit').serialize();
$.ajax({
url: '/php/quoteSend.php',
type: 'POST',
data: datastring
,
success: function(data) {
console.log(data);
if (data == 'Error!') {
alert('Unable to submit form!');
alert(data);
} else {
$('#salesforce_submit')[0].reset();
$('#consult-success').show();
$('#salesforce_submit').hide();
}
},
complete: function() {
//$("#salesforce_submit").submit();
location.href = "";
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
console.log('error');
}
});
}
});
Since jQuery Validate only validates select, textarea, and various types of input elements1, your only option is to give it what it wants.
Create a hidden element...
<input type="hidden" name="myImage" value="0" />
When the user clicks your image, use jQuery to manipulate the value of a type="hidden" input element...
$('#photo').on('click', function() {
$('[name="myImage"]').val('1');
});
And then programmatically validate its value instead. Since clicking on the image will not cause any validation, you can use the .valid() method to trigger validation on these hidden elements...
$('[name="myImage"]').valid();
You will need to leverage the ignore option since the plugin will not validate hidden elements by default. ignore: [] will effectively disable this and force the plugin to validate all hidden elements...
$('#salesforce_submit').validate({
ignore: [],
rules: { ....
Of course, you'll also need to have rules in place that properly validate the value of your hidden element.
Since the message will be placed near the hidden element, you'll have to leverage the errorPlacement function to place this message conditionally.
$('#salesforce_submit').validate({
ignore: [],
errorPlacement: function(error, element) {
if (element.attr('name') == 'myImage') {
// placement for hidden element
} else {
// default
error.insertAfter(element);
}
}
rules: { ....
1 newer versions of the plugin also support elements with the contenteditable attribute.
What about this, give all the checkboxes you trigger the same name e.g. "box". Add this custom rule "img_check":
jQuery.validator.addMethod("img_check", function() {
$(input[name='box']).each( function(){
if $(this).is(':checked') {
return true
}
})
// No box was checked
return false
}, "Please check at least one box");
Then add this rule:
rules: {
first_name: {
required: true,
minlength: 2
},
box[]: {
img_check: true
}
},
Why don't you check checkValue before going ahead with the submission process?
//Getting Value of the interest boxes
var interest = $('.interest');
var checkVal = '';
var checkValue = '';
interest.click(function() {
checkVal = [];
$(this).toggleClass('active');
$('.interestBox', this).toggleClass('active');
interest.each(function() {
if($(this).is('.active')) {
checkVal.push($(this).data('title'));
}
});
checkValue = checkVal.join(', ');
console.log(checkValue);
});
//Jquery Validate
$('#salesforce_submit').validate({
rules: {
first_name: {
required: true,
minlength: 2
}
},
messages: {
first_name: {
required: "Please enter your first name",
minlength: "Your first name seems a bit short, doesn't it?"
}
},
submitHandler: function(form) {
if(checkValue.length>0){
event.preventDefault();
var datastring = $('#salesforce_submit').serialize();
$.ajax({
url: '/php/quoteSend.php',
type: 'POST',
data: datastring
,
success: function(data) {
if (data == 'Error!') {
alert(data);
} else {
}
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
console.log('error');
}
});
}else console.log('Please select at least one interest');
}
});
.interest img {
height: 50px;
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form id="salesforce_submit" type="Post">
<div><input id="first_name" placeholder="First Name*" class="input block" maxlength="40" name="first_name" type="text"></div>
<h3 class="interestTitle">A</h3>
<div class="interest" data-title="A">
<img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="A">
</div>
<h3 class="interestTitle">B</h3>
<div class="interest" data-title="B">
<img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="B">
</div>
<h3 class="interestTitle">C</h3>
<div class="interest" data-title="C">
<img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="C">
</div>
<input type="Submit" value="Submit">
I have following input elements on my form and and validation form with jQuery validation plugin.
HTML:
<form name='frmUsers' id='frmUsers' method='post' action='#'>
<div>
<input type='text' name='name' id='name' placeholder='Name' />
</div>
<br />
<div>
<input type='text' name='fixed_budget' id='fixed_budget' placeholder='Fixed budget' />
</div>
<br />
<div>
<select name='budget' id='budget'>
<option value=''>Select your budget</option>
<option value='1000'>1000</option>
<option value='2000'>2000</option>
<option value='3000'>3000</option>
<option value='4000'>4000</option>
</select>
</div>
<br/>
<div>
<input id='save' type='submit' value='Save' />
</div>
</form>
jQuery validation:
$(document).ready(function () {
$("#frmUsers").validate({
onkeyup: false,
onfocusout: false,
ignore: [],
rules: {
"name": {
required: true
},
"fixed_budget": {
required: true
},
"budget": {
required: true
}
},
messages: {
"name": {
required: 'required'
},
"first_name": {
required: 'required'
},
"last_name": {
required: 'required'
}
},
errorPlacement: function (error, element) {
},
submitHandler: function () {
return false;
}
});
});
Now all elements are required fields but I have specific condition on Fixed budget (text box) and budget (select box).
For example:
When user click on submit, fixed budget and budget elements display with errors but (1) when user select any option on budget, set fixed budget field to not required. (2) when user input something on fixed budget set budget field to not required.
Here is my working JSFiddle: http://jsfiddle.net/mananpatel/85KR4/384/
Any Idea?
Thanks.
(1) when user select any option on budget, set fixed budget field to not required. (2) when user input something on fixed budget set budget field to not required.
In other words, you only require one of those two fields filled out.
Include the additional-methods.js file and use the require_from_group method.
rules: {
name: {
required: true
},
fixed_budget: {
require_from_group: [1, ".requiredGroup"]
},
budget: {
require_from_group: [1, ".requiredGroup"]
}
},
DEMO: http://jsfiddle.net/7om97gk8/
Note:
Use return false within the errorPlacement function if you want to suppress messages. Don't leave the function empty, as that's sloppy coding.
errorPlacement: function (error, element) {
return false;
},
Also, use the latest version of the plugin file as this will ensure the require_from_group method operates bug-free.
I don't understand why you are using the messages option when you've totally disabled these messages from displaying. You can safely remove messages in this case.
i am using Jquery validation plugin for validating the form.when validating the form for one element alignment is not proper.
If you see the image,for the city field icon + button alignment not proper when it validating the form. Because label error validation is displaying in between the input element and icon +. I need to display the error message below of the element.
My html code is like this for the city field
<tr>
<td align="right"><span class="mandetry">*</span> City:</td>
<td>
<div class="input-group" id="app_details">
<input type="text" class="form-control client_city" name="client_city" id="city_name" value="<?php echo set_value('client_city')?>">
<span class="input-group-btn">
<a class="btn btn-default" id='addnewcity' href="<?php echo base_url('addnewcity')?>"><i class="fa fa-plus-square"></i></a>
</span>
<div id="messageBox"></div> <!-- Here i would like to display message-->
</div> </tr>
js code is like this
$(document).ready(function(){
$('#add_client').validate({
errorClass: 'validation_errors',
debug: false,
rules: {
client_name:{required:true},
client_address:{required:true},
client_city:{required:true},
errorPlacement: function(error, element) {
if (element.attr("name") == "client_city" )
{
error.appendTo("#messageBox");
}
}
},
messages: {
client_name:{required:"The Client name is a required / mandatory field"},
client_address:{required:"The Client address is a required / mandatory field"},
client_city:{required:"The City is a required / mandatory field"},
}
});
});
Error message not appended to messageBox div.Is there any wrong with errorPlacement in js. For only city element i need to display the error message properly. For other form fields it shouldn't change.i am unable to solve this issue. Please suggest me. Thanks.
You are missing the else part, if it is not the client_city element then you need to insert the error after
$(document).ready(function () {
$('#add_client').validate({
errorClass: 'validation_errors',
debug: false,
rules: {
client_name: {
required: true
},
client_address: {
required: true
},
client_city: {
required: true
}
},
errorPlacement: function (error, element) {
console.log('dd', element.attr("name"))
if (element.attr("name") == "client_city") {
error.appendTo("#messageBox");
} else {
error.insertAfter(element)
}
},
messages: {
client_name: {
required: "The Client name is a required / mandatory field"
},
client_address: {
required: "The Client address is a required / mandatory field"
},
client_city: {
required: "The City is a required / mandatory field"
},
}
});
});
Demo: Fiddle
How do you create a simple, custom rule using the jQuery Validate plugin (using addMethod) that doesn't use a regex?
For example, what function would create a rule that validates only if at least one of a group of checkboxes is checked?
You can create a simple rule by doing something like this:
jQuery.validator.addMethod("greaterThanZero", function(value, element) {
return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");
And then applying this like so:
$('validatorElement').validate({
rules : {
amount : { greaterThanZero : true }
}
});
Just change the contents of the 'addMethod' to validate your checkboxes.
$(document).ready(function(){
var response;
$.validator.addMethod(
"uniqueUserName",
function(value, element) {
$.ajax({
type: "POST",
url: "http://"+location.host+"/checkUser.php",
data: "checkUsername="+value,
dataType:"html",
success: function(msg)
{
//If username exists, set response to true
response = ( msg == 'true' ) ? true : false;
}
});
return response;
},
"Username is Already Taken"
);
$("#regFormPart1").validate({
username: {
required: true,
minlength: 8,
uniqueUserName: true
},
messages: {
username: {
required: "Username is required",
minlength: "Username must be at least 8 characters",
uniqueUserName: "This Username is taken already"
}
}
});
});
// add a method. calls one built-in method, too.
jQuery.validator.addMethod("optdate", function(value, element) {
return jQuery.validator.methods['date'].call(
this,value,element
)||value==("0000/00/00");
}, "Please enter a valid date."
);
// connect it to a css class
jQuery.validator.addClassRules({
optdate : { optdate : true }
});
Custom Rule and data attribute
You are able to create a custom rule and attach it to an element using the data attribute using the syntax data-rule-rulename="true";
So to check if at least one of a group of checkboxes is checked:
data-rule-oneormorechecked
<input type="checkbox" name="colours[]" value="red" data-rule-oneormorechecked="true" />
addMethod
$.validator.addMethod("oneormorechecked", function(value, element) {
return $('input[name="' + element.name + '"]:checked').length > 0;
}, "Atleast 1 must be selected");
And you can also override the message of a rule (ie: Atleast 1 must be selected) by using the syntax data-msg-rulename="my new message".
NOTE
If you use the data-rule-rulename method then you will need to make sure the rule name is all lowercase. This is because the jQuery validation function dataRules applies .toLowerCase() to compare and the HTML5 spec does not allow uppercase.
Working Example
$.validator.addMethod("oneormorechecked", function(value, element) {
return $('input[name="' + element.name + '"]:checked').length > 0;
}, "Atleast 1 must be selected");
$('.validate').validate();
<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.14.0/jquery.validate.min.js"></script>
<form class="validate">
red<input type="checkbox" name="colours[]" value="red" data-rule-oneormorechecked="true" data-msg-oneormorechecked="Check one or more!" /><br/>
blue<input type="checkbox" name="colours[]" value="blue" /><br/>
green<input type="checkbox" name="colours[]" value="green" /><br/>
<input type="submit" value="submit"/>
</form>
Thanks, it worked!
Here's the final code:
$.validator.addMethod("greaterThanZero", function(value, element) {
var the_list_array = $("#some_form .super_item:checked");
return the_list_array.length > 0;
}, "* Please check at least one check box");
You can add a custom rule like this:
$.validator.addMethod(
'booleanRequired',
function (value, element, requiredValue) {
return value === requiredValue;
},
'Please check your input.'
);
And add it as a rule like this:
PhoneToggle: {
booleanRequired: 'on'
}
For this case: user signup form, user must choose a username that is not taken.
This means we have to create a customized validation rule, which will send async http request with remote server.
create a input element in your html:
<input name="user_name" type="text" >
declare your form validation rules:
$("form").validate({
rules: {
'user_name': {
// here jquery validate will start a GET request, to
// /interface/users/is_username_valid?user_name=<input_value>
// the response should be "raw text", with content "true" or "false" only
remote: '/interface/users/is_username_valid'
},
},
the remote code should be like:
class Interface::UsersController < ActionController::Base
def is_username_valid
render :text => !User.exists?(:user_name => params[:user_name])
end
end
Step 1 Included the cdn like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
Step 2 Code Like
$(document).ready(function(){
$("#submit").click(function () {
$('#myform').validate({ // initialize the plugin
rules: {
id: {
required: true,
email: true
},
password: {
required: true,
minlength: 1
}
},
messages: {
id: {
required: "Enter Email Id"
},
password: {
required: "Enter Email Password"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
}):
});