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 am trying to validate a form using jquery validation and I keep receiving an error "Uncaught TypeError: Cannot read property 'settings' of undefined".
The error is coming from the jquery-latest.min.js file and my jquery.validate.min.js file. Any suggestions on how to fix this?
Also, when I remove validationObj.form(); block, the error goes away, but then the validation rules are not running.
Here is my HTML:
<div id="contactForm">
<p>Contact Information</p></br>
<div id="contactInfo">
<label>First Name:</label>
<input type="text" name="fName" id="fName"/></br>
<label>Last Name:</label>
<input type="text" name="lName" id="lName"/></br>
<label>Email:</label>
<input type="text" name="email" id="email"/></br>
<label>Phone:</label>
<input type="text" name="phone" id="phone"/></br>
</div></br>
And here is my js:
var validationObj = $("#contactForm").validate
(
{
rules:
{
fName:{required:true},
lName:{required:true},
email:{required:true, email:true},
},//End rules
messages:
{
fName:{equalTo:"Please enter your first name"},
lName:{equalTo:"Please enter your last name"},
email:{minlength:"Please enter a valid email"},
},//End messages
errorPlacement:
function(error, element)
{
error.appendTo( element.next());
}
}//End validationObj
);//End var validationObj
validationObj.form();
$("form").submit
(function(e)
{
if(!validationObj.form())
{
alert("Form Errors");
}
}
);
}
Wrapped it in a form and removed the call before the submit. Working fiddle.
var validationObj = $("#contactForm").validate({
rules: {
fName: {
required: true
},
lName: {
required: true
},
email: {
required: true,
email: true
},
}, //End rules
messages: {
fName: {
equalTo: "Please enter your first name"
},
lName: {
equalTo: "Please enter your last name"
},
email: {
minlength: "Please enter a valid email"
},
}, //End messages
errorPlacement: function(error, element) {
error.appendTo(element.next());
}
} //End validationObj
); //End var validationObj
$("#contactForm").submit(function(e) {
if (!validationObj.form()) {
alert("Form Errors");
} else {
alert("Form Valid");
}
});
I want to check my field is nil, then return true otherwise check email validation. My field name is app_email.
$.validator.addMethod("checkEmail", function(app_email, element) {
var result;
if (condition) {
result = (app_email === "NIL") ? true : false;
} else {
preg_match( /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/,app_email);
return true;
}
},
"Email id is not valid."
);
html
<div class="control-group">
<label class="control-label">E-mail ID<span class="required">*</span></label>
<div class="controls">
<input type="text" class="span6 m-wrap" name="app_email" title="Enter Email Id">
</div>
</div>
If you are using jQuery Validation, you can use the default function like this.
You can refer to this link.
$( "#myform" ).validate({
rules: {
fieldNameHere: {
required: true,
email: true
}
}
});
Check if the value is 'NIL' return true, otherwise, validate email.
$.validator.addMethod("checkEmail",
function(value, element) {
return value === "NIL" ? true : /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/.test(value);
},
"Email id is not valid."
);
Demo
You can use radio button check inside custom validation like below.
JS:
jQuery.validator.addMethod("checkEmail", function (value, element) {
if ($('input:radio').is(':checked')) {
if (/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/.test(value)) {
return true;
} else {
return false;
}
} else {
return true;
}
}, "Email id is not valid.");
$('#myform').validate({
rules: {
email: {
checkEmail: true
}
}
});
HTML:
<form id="myform">
<input type="radio" value="">
<input name="email" id="email" type="text"/>
<input type="submit" />
</form>
In this example, email validation will be perform if the radio button is selected.
Guys I am using jQuery Validation plugin to validate the Input Text fields...
like this:
$("#formSettings").validate({
rules: {
sta: {
required: true,
},
crs: {
equalTo: "#password"
}
},
messages: {
email: {
required: "Please Provide Your Email Address",
email: "Provide Valid Email Address"
},
});
The issue: I need to match one textfield value with the other, each textfield have comma separated values and they should match before continuing, any idea how can I do that
like if textfield 1 is: 1,2,3,4,5,6 then textfield2 should match.
$('#selector').val().length
Above the basic jQuery version of .length After that you could do an if statement. Here is a brief untested test you try:
<input type="text" value="1,2,3,4,5" id="thing1">
<input type="text" value="1,2,3,4" id="thing2">
<input type="button" name="submit" value="submit" id="submit">
$('#submit').click(function(event){
var thing1 = $('#thing1').val().length;
var thing2 = $('#thing2').val().length;
if (thing1 == thing2) {
return true;
} else {
alert("Contents must have same length");
return false;
}
});
And the fiddle: http://jsfiddle.net/8XQB3/