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);
});
});
Related
I have a custom method
$.validator.addMethod("lettersandspaces", function(value, element) {
var value = this.elementValue(element).replace(/\s+/g, ' ').trim();
return this.optional(element) || /^[a-zA-Z][a-zA-Z\s]*$/i.test(value);
}, 'Your name may only contain letters');
Here I am trimming whitespace and replacing any repeating whitespaces with only one. I am then validating to make sure there are only letters and spaces.
Is it possible to make it so the trimmed value is submitted with the form instead of what the user entered?
Use the submitHandler and you can make any action before submiting the form ,(form.submit())
See beleow a working snippet
$.validator.addMethod("lettersandspaces", function(value, element) {
var value = this.elementValue(element).replace(/\s+/g, ' ').trim();
return this.optional(element) || /^[a-zA-Z][a-zA-Z\s]*$/i.test(value);
}, 'Your name may only contain letters');
$(document).ready(function () {
$("#form").validate({
rules: {
"name": {
required: true,
minlength: 5,
lettersandspaces: true
},
"age": {
required: true,
}
},
messages: {
"name": {
required: "Please, enter a name"
},
"age": {
required: "Please, enter your age",
}
},
submitHandler: function (form) { // for demo
var newName = $("#name").val().replace(/\s+/g, ' ').trim()
$("#name").val(newName);
$(form).valid();
alert("Name = '"+newName+"'");
// comment return and uncomment form.submit(
return false; //form.submit();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<form id="form" method="post" action="#">
<label for="name">Name :</label>
<input type="text" name="name" id="name" /><br><br>
<label for="age">Age : </label>
<input type="age" name="age" id="age" /><br><br>
<button type="submit">Submit</button>
</form>
In validation form by jquery. If you want change value input name before validate. Let try:
$('#form').validate({
rules: {
'name': {
normalizer: function(){
return $('#name').val().(/\s+/g, ' ').trim();
}
}
}
})
When I use 'ignore' of validate() method, submission has been proceeded regardless of the result of validation(good or bad).
It is like 'ignore' make validation of all input elements bypass. So even if one or more input elements don't satisfy conditions for validation, the form has been submitted and server will work.
Oh, in my case, 'ignore' makes submitHandler and (even!) invalidHandler not work either.
What's wrong point? Here's my sampled(not entire) code below.
$('#frm').validate({
submitHandler: function() {
var applyMsg = "Proceed?";
var f = confirm(applyMsg);
if(f) {
//console.log(" confirm : "+ f );
return true;
} else {
//console.log(" no confirm : "+ f );
return false;
}
},
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
alert(validator.errorList[0].message);
validator.errorList[0].element.focus();
}
},
ignore: '.ignore',
rules: {
PHOTO_PLACE: {photo_place: true}
},
messages: {
PHOTO_PLACE: {required: ""},
ENT_DATE: {minlength: "", maxlength: ""}
}
});
<form id="frm" name="frm" method="post" class="app_frm">
<input type="hidden" id="PHOTO_PLACE" name="PHOTO_PLACE" />
<input type="text" name="ENT_DATE" minlength="8" maxlength="8" class="ignore" />
</form>
Thank you for any help.
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[]"]');
}
}
}
});
}
});
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
}
});
}):
});
I have small form :
Following is the script where I am validating the required field for input field which is working perfectly now I want to validate url using jquery.validate.min.js.
<script type="text/javascript" >
$(document).ready(function() {
var container = $('#error');
$("#rssform").validate({
errorContainer: container,
errorLabelContainer: $(container),
meta: "validate",
rules: {
feedurl: {
required:true
}
},
messages: {
feedurl: {
required:"Please Enter the URL"
}
}
});
});
</script>
<form action="rssindex.php" method="POST" id="rssform">
<label>Enter the feed URL </label>
<input type="submit" name="submit" value="GO" id="submit"/>
</form>
How can I do this. Any solution?
Thanks
jQuery validate plugin provide method to validate url.
Example:
$("#myform").validate({
rules: {
field: {
required: true,
url: true
}
}
});
For your code, add url: true to the rules.
feedurl: {
required:true,
url: true //here
}