This question already has answers here:
jQuery Validate Plugin - How to create a simple custom rule?
(8 answers)
Closed 8 years ago.
I am trying to override the functionality of 'required' and 'minlength' validators provided by jQuery Validator plugin. Following is my code:
jQuery(".form-cls").validate({
errorElement: "span",
errorClass: "error-msg",
rules: {
email:{
required:true,
email:true,
alreadyExistEmail: true
},
user_email:{
required:true,
email:true
},
password:{
required: function (element) {
return checkIfPasswordIsRequired();
},
minlength: function (element) {
return passwordLengthCheck(element);
}
}
}
});
function checkIfPasswordIsRequired()
{
if(jQuery("#facebook_id").length > 0 || jQuery("#linkedin_id").length > 0 || jQuery("#xing_id").length > 0) {
if(jQuery("#facebook_id").val() != "" || jQuery("#linkedin_id").val() != "" || jQuery("#xing_id").val() != "") {
return false;
}
}
return true;
}
function passwordLengthCheck(element)
{
if(element.value.length < 6)
{
return false;
}
else
{
return true;
}
}
Now here the first check on password field is working fine that is of 'required' but the second check is not working. If have checked it my console.log(element.value.length) and it gives the length of value in password field each time the value is changed/altered but depending on the condition in function passwordLengthCheck it never shows/displays error. Kindly help!!
To check field length, just add minlength attribute to the <input> tag, like
<input id="pw" name="pw" minlength="6" type="password">
To add some custom validation, use addMethod():
jQuery.validator.addMethod("func", function(value, element) {
return this.optional(element) || check expression here;
}
Related
EDIT2:
I feel I'm near the solution. Following the vicgoyso's suggestion I created some object from my inputs (and not arrays), and then I compared them: see the jsfiddle
Since this comparison is working: comparison on jsfiddle I would expect the code above to work as well, but it's not.
EDIT:
The jQuery method I was working on is similar to this:
$().ready(function(){
$.validator.addMethod("same_names", function(value, element) {
if (!$('#surname').val() || $('#surname').val() != null
&& !$('#surname1').val() || $('#surname1').val() != null){
return $('#name').val() != $('#name1').val()
&& $('#surname').val() != $('#surname1').val()
&& $('#nickname').val() != $('#nickname1').val()
}
}, " Your input is equal to another");
$("#myForm").validate({
rules: {
name: {
required: false,
same_names: true
},
name1: {
required: false,
same_names: true
},
surname: {
required: false,
same_names: true
},
surname1: {
required: false,
same_names: true
},
nickname: {
required: false,
same_names: true
},
nickname1: {
required: false,
same_names: true
},
},
messages: {
...
}
})
});
It continue say that name, surname and nickname are required, and they are not.
Without jQuery my method is similar to this:
$('#myForm').submit(function (event) {
var errors = false;
if ($('#name').val() == $('#name1').val() &&
$('#surname').val() == $('#surname1').val() &&
$('#nickname').val() == $('#nickname1').val()
||
$('#name').val() == $('#name2').val() &&
$('#surname').val() == $('#surname2').val() &&
$('#nickname').val() == $('#nickname2').val()
||
$('#name').val() == $('#name3').val() &&
$('#surname').val() == $('#surname3').val() &&
$('#nickname').val() == $('#nickname3').val()
||
$('#name').val() == $('#name4').val() &&
$('#surname').val() == $('#surname4').val() &&
$('#nickname').val() == $('#nickname4').val()
....
||
$('#name').val() == $('#name10').val() &&
$('#surname').val() == $('#surname10').val() &&
$('#nickname').val() == $('#nickname10').val()
||
$('#name1').val() == $('#name2').val() &&
$('#surname1').val() == $('#surname2').val() &&
$('#nickname1').val() == $('#nickname2').val()
||
$('#name1').val() == $('#name3').val() &&
$('#surname1').val() == $('#surname3').val() &&
$('#nickname1').val() == $('#nickname3').val()
.... and so on
) {
$("#error").show();
location.href = "#";
location.href = "#error";
errors = true;
} else {
errors = false;
$("#error").hide();
}
if (errors == true) {
event.preventDefault();
}
});
My actual jsp is similar to this (there are 10 input groups, formed by name + surname + nickname):
<form id="myForm" method="post">
<input id="name" name="name" />
<input id="surname" name="surname" />
<input id="nickname" name="nickname" />
<br/ >
<input id="name1" name="name1" />
<input id="surname1" name="surname1" />
<input id="nickname1" name="nickname1" />
<br/>
<input id="name2" name="name2" />
<input id="surname2" name="surname2" />
<input id="nickname2" name="nickname2" />
<br />
<input id="name3" name="name3" />
<input id="surname3" name="surname3" />
<input id="nickname3" name="nickname3" />
<br />
<br />
<input id="submit" type="submit" value="submit" />
</form>
I want to be an error just if one of this group (name, surname, nickname) is equal to another, for example this is an error:
John
Smith
prince *
John
Smith
prince *
John
Smith
snowman
But this one is not:
John
Smith
prince at least one field is different so the input is fine
John
Smith
snowman *at least one field is different so the input is fine
John
Smith
fireball at least one field is different so the input is fine
QUESTION
What if I want to use this code: https://stackoverflow.com/a/16965721/4477899
To solve this problem here: Form validate some input must be different from each other
I'm asking because I'm already using jQuery validate, and the previous approach is not working well if fields are more than two groups, or are empty (those fields are not required).
Regarding this part only:
EDIT2:
I feel I'm near the solution. Following the vicgoyso's suggestion I created some object from my inputs (and not arrays), and then I compared them: see the jsfiddle
Since this comparison is working: comparison on jsfiddle I would expect the code above to work as well, but it's not.
You failed to include jQuery itself in the jsFiddle.
Mainly it wouldn't work anyway because your boolean logic is backwards. You are getting true when you find a match. However, you then return true from the addMethod() method, so with a true you are telling it to PASS validation. To fail validation, you must return false instead.
return !duplicateFound;
Finally, to make the fields optional, you'll need a little more logic...
return this.optional(element) || !duplicateFound;
DEMO: https://jsfiddle.net/awb4tcyy/3/
As a general note, your code will get incredibly complex as you scale with more groups of fields. I would suggest you leverage some type of looping algorithm. Good luck.
You first need to define a custom validation method:
https://jqueryvalidation.org/jQuery.validator.addMethod/
jQuery.validator.addMethod("laxEmail", function(value, element) {
var duplicateFound = false;
//apply input values in array
//check for duplicates
duplicateFound = true; //update variable if duplicate found
return duplicateFound;
}, 'Input values cannot be identical');
In your custom validation, get/store the input values in an array:
jQuery get values from inputs and create an array
then check array for duplicates, return true if duplicate is found:
How can I check if the array of objects have duplicate property values?
You then add the name of your custom validation rule to the input validation like so:
myForm.validate({
rules: {
myCustomRule: {
required: true
}
},
messages {
myCustomRule: {
required: "Input values cannot be identical"
}
}
});
I want to use jquery validate() rule to 2 cross fields. If either of the field is typed in the other one is also required. Also, once they are required there format for number field should be 1st 15 digits should be integer and date field should be mm/dd/yyyy format and date should be less than todays date.
//..
$("#adjustmentsFormID").validate({
rules: {
refTranNbr: "required",
refTranDate: "required"
},
messages: {
refTranNbr: {
required: function (element) {
if($("#refTranDate").val().length > 0){
return "Please enter the reference transaction number ";
} else if(!refNumChk($("#refTranNbr").val())){
return "Please enter a valid Reference Transaction Number";
} else {
return false;
}
}
},
refTranDate: {
required : function (element) {
var tdate = $("#refTranDate").val();
if($("#refTranNbr").val().length > 0){
return "Please enter a date for the Refering Transaction to complete this transaction.";
}else if((new Date() > new Date(tdate))) {
return "Please enter a reference transaction date less than today's date.";
}else{
return false;
}
}
},
});
..//
In both the cases the 1st condition for required field works. However for refNum field the 2nd condition which has refNumChk isnot working. Actually its not getting called. Similarly for refTranDate required field validation works however date > tDate is not getting checked. Not sure if this method would work or should i do something different for multiple conditions.
Your approach to jQuery validation is wrong, the messages is used to return only the error message in case of an validation error.
So the only validation you are doing is the required validation, you can add custom validation rules to solve this
jQuery(function($) {
jQuery.validator.addMethod("refNumChk", function(value, element, params) {
return this.optional(element) || /^\d{15}[A-Z]$/.test(value);
}, jQuery.validator.format("Enter a value in forat aa-999"));
jQuery.validator.addMethod("lessThanToday", function(value, element, params) {
return this.optional(element) || new Date() > new Date(value);
}, jQuery.validator.format("Value should be less than today"));
$("#adjustmentsFormID").validate({
rules: {
refTranNbr: {
required: true,
//refNumChk: true
pattern: /^\d{15}[A-Z]$/
},
refTranDate: {
required: true,
lessThanToday: true
}
},
messages: {
refTranNbr: {
required: "Please enter the reference transaction number",
pattern: "Please enter a valid Reference Transaction Number"
},
refTranDate: {
required: "Please enter a date for the Refering Transaction to complete this transaction.",
lessThanToday: "Please enter a reference transaction date less than today's date."
},
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>
<form id="adjustmentsFormID" method="post" action="">
<div>
<input name="refTranNbr" />
</div>
<div>
<input name="refTranDate" />
</div>
<input type="submit" value="Save" />
</form>
I was trying to make a validation in my form with jquery, but it does not work the way it was supposed to and I have no idea why.
I have this function to make the validation:
function newLogin () {
var username = $("#popup-login-email").val();
var password = $("#popup-login-password").val();
if (username == "" || password.length<5){
$(document).ready(function () {
$("#popup-login-form").validate({ // initialize the plugin
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
});
});
return false;
}
else{
Parse.User.logIn(username, password, {
success:function(user){
console.log("login successfull");
if(checkEmail()){
console.log(checkEmail());
document.location.href = "Temas.html";
}
},
error: function(user, error){
console.log(error.message);
displayErrorDiv();
}
})
}
}
And i got this form
<form id = "popup-login-form">
<input type="email" name="email" placeholder="Email" id = "popup-login-email" class="popup-input first"/>
<div id="error-message-email" class="error">
</div>
<input type="password" name="password" placeholder = "Password" id="popup-login-password" class="popup-input"/>
<div id="error-message-password" class="error">
</div>
<button class="popup-button" id="popup-cancel">Cancel</button>
<button type="submit" class="popup-button" id="popup-submit">Login</button>
<div class="error-message-login" class="error">
</div>
</form>
And the weird part is that just does not work in my page. Here it works, for example: http://jsfiddle.net/xs5vrrso/
There is no problem with the code which you shared in jsfiddle but the above code you are using $(document).ready({function()}) inside a function which is of no use. Now the problem is that the method newLogin is not called on dom ready and thus this issue occurs.
Better keep the function call inside $(document).ready({function() newLogin() }) . Now you can also use submitHandler in validate to merge the if else conditions.
i make one example to you
jsfiddler example
$(document).ready(function () {
$("#popup-login-form").validate({ // initialize the plugin
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
});
//event listening onSubmit
$('form').submit(function(event){
var returnForm = true;
var username = $("#popup-login-email").val();
var password = $("#popup-login-password").val();
//Make your validation here
if (username == "" || password.length<5){
returnForm = false;
}
return returnForm; //Submit if variable is true
});
});
With jQuery when i get the
"TypeError: $(...).validate is not a function"
I change
$(..).validate
for
jQuery(..).validate
You have to include this validate file after jquery file.
<script src="http://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.js"></script>
Do not wrap the code under the if condition with $(document).ready(). Change the code to :
if (username == "" || password.length < 5){
$("#popup-login-form").validate({ // initialize the plugin
/*remaining code here*/
});
}
Also it is a good habit to trim the spaces around any input that you accept from the users. For e.g in your case please do the following:
var username = $.trim($("#popup-login-email").val());
var password = $.trim($("#popup-login-password").val());
/* $.trim() would remove the whitespace from the beginning and end of a string.*/
I have an input form that I'm performing client-sided validation on with the jQuery validator plugin. Basic usage is working great, except for a specific scenario:
The form splits up address input fields, allowing separate fields for street number, name, city, state, and zip. The address itself is an optional input to the form (a user may opt to enter no address), but I want to ensure that if any one of these fields are used, the user is prompted to enter all the fields.
This works, except in the case when someone enters in an address and hits submit, and then decides to enter in no address. The ideal behavior in this case would be that, as soon as the text in the inputs they've entered is removed, for the address group to be unhighlighted.
Here is the current scenario:
User enters information into only one input field, e.g., street name.
The submit button is clicked.
The validator plugin highlights the other address inputs with an error message prompting for the full address.
User decides to enter no address, and removes the prior input, e.g. erases street name
Ideally: All the other highlighted address inputs are unhighlighted and the error message is removed. Actually: The highlighted address inputs and message remain until form submission.
Here is the javascript that demonstrates the problem and the corresponding JSFiddle.
$("form").validate({
errorClass: 'error',
errorElement: 'label',
submitHandler: function() {
alert("Form submitted");
return false;
},
groups: {
address: "streetNumber streetName city state zipcode"
},
rules: {
streetNumber: {
required: {
depends: function(){
return $("#streetName").val() != '' || $("#city").val() != '' || $("#state").val() != '' || $("#zipcode").val() != '';
}
}
},
streetName: {
required: {
depends: function(){
return $("#streetNumber").val() != '' || $("#city").val() != '' || $("#state").val() != '' || $("#zipcode").val() != '';
}
}
},
city: {
required: {
depends: function(){
return $("#streetNumber").val() != '' || $("#streetName").val() != '' || $("#state").val() != '' || $("#zipcode").val() != '';
}
}
},
state: {
required: {
depends: function(){
return $("#streetNumber").val() != '' || $("#streetName").val() != '' || $("#city").val() != '' || $("#zipcode").val() != '';
}
}
},
zipcode: {
required: {
depends: function(){
return $("#streetNumber").val() != '' || $("#streetName").val() != '' || $("#city").val() != '' || $("#state").val() != '';
}
}
}
},
messages: {
streetNumber: {required: "Must provide full address"},
streetName: {required: "Must provide full address"},
city: {required: "Must provide full address"},
state: {required: "Must provide full address"},
zipcode: {required: "Must provide full address"}
},
highlight: function(element, errorClass, validClass) {
$(element).addClass(errorClass).removeClass(validClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass(errorClass);
},
errorPlacement: function(error, element) {
var n = element.attr("name");
if (n == "streetNumber" || n == "streetName" || n == "city" || n == "state" || n == "zipCode")
error.insertAfter("#zipcode");
}
});
Besides trying to get the desired functionality of the highlight, I'm also wondering if there is a smarter way to accomplish the "all or nothing" input groups that doesn't involve the mess of conditional statements. Perhaps I can use a form input group?
You need to add a function on the focus event, then when the user leaves the field, the form fields will update.
It's difficult because you are using a plugin, so all the calls are happening inside that but I think something like this will work:
var inputs = $('form').find('input');
inputs.focus(function () {
inputs.each(function () {
$(this).removeClass('error');
});
});
Just stick this in your code outside of the validate initialiser.
It would be even better if you defined your errorCode variable outside of the validator and then used that var in both functions, like this:
var errorClass = 'error';
$('form').validate({
errorClass: errorClass,
...
...
});
var inputs = $('form').find('input');
inputs.focus(function () {
inputs.each(function () {
$(this).removeClass(errorClass);
});
});
you can try to add a method in the
unhighlight:
something like
$('.error').removeClass(errorClass);
or define related inputs and do
$('.relatedInputs').removeClass(errorClass);
you could also add an onChange function like
function(el){
if(el.val() == ''){
$('.relatedInputs').removeClass(errorClass);
}
}
I was able to get desired functionality by using this:
onfocusout: function(element) {
var inputs = $(element).closest('form').find('input, select');
inputs.each(function() {
if ($(this).valid())
$(this).removeClass('error');
});
}
Which was inspired from another post and DoubleA's answer. I haven't tested it thoroughly to see if it regresses anything, but so far it seems to work.
I'm trying to use tinymce's getContent() to make a custom validation rule, how can I do this with jquery validation? I need to apply the rule to a textarea formatted with tinymce.
Validation: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
$("#element").click( function(e) {
console.log(tinyMCE.activeEditor.getContent());
$("#someForm").validate({
rules: {
title: {
required: true
}
}
});
});
I'm thinking of just using a little bit of javascript with getContent() because it looks like there's just as much effort creating a workaround to get jquery validation working with tinymce. Thoughts on possible solutions?
The following stackoverflow questions should help you on that issue:
validating multiple TinyMCE Editor
Jquery validation form with TinyMCE field who gives no error by empty value
Hi if your are not getting client side validation on form submit time when you are with tinymce try this code
suppose your have two html editor 1 is txtAboutCompanyand 2 is txtProductinfo
this is client side code
<div class="divclass">
#Html.LabelFor(model => model.txtAboutCompany, new { #class = "required" })
#Html.EditorFor(model => model.txtAboutCompany)
<span class="field-validation-error" id="AC" style="margin:9px 0 0 157px;"></span>
</div>
this is jquery
$("#BusinessProfile").click(function () {
var aboutC = $("#txtAboutCompany").val()
var pinfo = $("#txtProductinfo").val();
if (aboutC == "" && pinfo == "") {
$("#AC").append("").val("").html("Please enter about company")
$("#PI").append("").val("").html("Please enter product information")
$("#bpform").valid();
return false;
} else if (aboutC == "") {
$("#PI").append("").val("").html("")
$("#AC").append("").val("").html("Please enter about company")
$("#txtAboutCompany").focus();
$("#bpform").valid();
return false;
} else if (pinfo == "") {
$("#AC").append("").val("").html("")
$("#PI").append("").val("").html("Please enter product information")
$("#txtProductinfo").focus();
$("#bpform").valid();
return false;
}
else {
$("#AC").append("").val("").html("");
$("#PI").append("").val("").html("");
//return true;
$("#bpform").validate();
}
});
you can get your all required validation on form submit time
I know this is not proper way but you can do it .
function tinymceValidation() {
var content = tinyMCE.activeEditor.getContent();
if (content === "" || content === null) {
$("#questionValid").html("<span>Please enter question statement</span>");
} else {
$("#questionValid").html("");
}
}
tinymce.activeEditor.on('keyup', function (e) {
debugger;
tinymceValidation();
});
$(form).submit(function (e) {
tinymceValidation();
});