jQuery Validation giving error with every character entered - javascript

I'm using jQuery Validator on a form on my site. It is functioning properly, but every keystroke results in an error:
Uncaught TypeError: Object #<error> has no method 'call'
I am implementing validation through classes on each field and all that is working properly - required fields, email fields, numbers, etc.. Here is my validate code:
if(jQuery().validate) {
//assign to global var for manual validation
validator = $(".validated").validate({
errorClass: "help-inline text-error",
errorElement: "span",
invalidHandler: function(e, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'Please fix the indicated field before saving this form.'
: 'Please fix the errors on the indicated fields before saving this form.';
$(".validation-message").text(message);
$(".validation-message").addClass('alert alert-error');
} else {
$(".validation-message").removeClass('alert alert-error').text("");
}
},
onkeyup: true,
submitHandler: function(form) {
$(".validation-message").removeClass('alert alert-error').text("");
form.submit();
},
errorPlacement: function(error, element) {
if(element.parent().hasClass('input-append')){
error.insertAfter( element.parent() );
}else{
error.insertAfter(element);
}
}
});
}
Can anyone see what would trigger that error without impacting functionality?
Cheers!

There is no true value for onkeyup option.
By default the field validation is enabled during keyup event. You need to use this option only in two scenarios
To disable validation during keyup event, in that case set onkeyup: false
To customize field validation during keyup
In your case you can just remove the option onkeyup.

Related

How can I force jquery validator to trigger validation method even if form values are unchanged

I have a small aspx form, which I validate using jquery validator.
var validator = $('form').validate({
invalidHandler: function (event, validator) {
errorsCount.Count = errorsCount.Count + 1;
if (errorsCount.Count >= 3) {
window.location.replace("http://" + window.location.hostname + ":" + window.location.port + "/RequestError.aspx");
}
},
submitHandler: function (form) {
errorsCount.Count = 0;
form.submit();
},
rules: {
txtFirstName: {
required: true,
maxlength: 50,
containsAlphaCharacter: true
}
},
onkeyup: false,
messages: {
txtFirstName: {
required: EnrollmentValidationMessages.English.REQUIRED_FIELD,
maxlength: EnrollmentValidationMessages.English.MAX_STRING_LENGTH
}
}
});
With this setup, if I cause a validation error on any of the fields and hit the submit button, the method will run just fine. However, if I hit the submit button again, the method won't be run. This is what I need to work around. Basically I need the invalidHandler to run EVERY TIME user clicks on the button, regardless of form values being changed or not.
The jquery validator will cache the previous value once the form is submitted. Unless you change the value which is invalid or change any of the field's value in your form it will not submit.
To force jquery validator to revalidate again without changing the field value, you have to remove the previously cached value from the jquery validator.
To do this, place this line of code on the top, before calling the validator.
$("#form :input").removeData("previousValue");
or if you want to remove only the specific value then,
$("#txtFirstName").removeData("previousValue");
This will work.

jQuery validation no of error count number

I am currently working on jQuery validation; the current code I have was working fine, I am getting the number of error count. But I am not getting when the user enter the value in the corresponding field the error count has to detect one by one.
For example if I have 5 fields are not entered by the user it should say You have missed 5 fields. Please fill before submitted when all fields are entered the error field has to disable. And I need to highlight the label of the radio input when nothing is selected. Moreover I am trying to change my mandatory star from black to red. That is also not happening.
Here is my jQuery code.
$(document).ready(function () {
$("#basicForm").validate({
invalidHandler: function(event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You have missed ' + errors + ' fields. Please fill before submitted.';
$("#error_message").html(message);
$(".error_msge").show();
$("div.error").show();
$("#error_message").addClass("error_msge");
} else {
$("div.error").hide();
$("#error_message").removeClass("error_msge");
}
},
errorPlacement: function(error, element) {
},
onkeyup: false,
highlight: function(element) {
$(element).addClass('errRed');
$(element).addClass('text-error-red');
},
unhighlight: function(element) {
$(element).removeClass('errRed');
$(element).removeClass('text-error-red');
},
rules: {
txt_Fname: "required",
txt_lname: "required",
txt_Mfname: "required",
txt_Mlname: "required",
txt_Pptnum: "required",
txt_Pi: "required",
txt_dob: "required",
txt_Idt:"required",
txt_Epdt:"required",
sel_ms:"required",
ipt_nation:"required",
ipt_countryres:"required",
sel_rg:"required",
sel_sem:"required",
ipt_acdem:"required",
gender:"required"
}
});
});
Here is the Fiddle link.
You have lots of issues and I strongly recommend that you review the documentation.
But I am not getting when the user enter the value in the corresponding field the error count has to detect one by one for example If I have 5 fields are not entered by the user it should say You have missed 5 fields.
You have used the wrong option. The invalidHandler only fires on an invalid form, so when there are zero errors your function will never be called and it will be stuck on show "1 error". Use the showErrors option instead.
showErrors: function (errorMap, errorList) {
var errors = this.numberOfInvalids();
if (errors) {
var message = errors == 1 ? 'You missed 1 field. It has been highlighted' : 'You have missed ' + errors + ' fields. Please fill before submitted.';
$("#error_message").html(message);
$(".error_msge").show();
//$("div.error").show(); // superfluous
//$("#error_message").addClass("error_msge"); // superfluous
} else {
$(".error_msge").hide();
//$("div.error").hide(); // superfluous
//$("#error_message").removeClass("error_msge"); // superfluous
}
// ensures that highlight/unhighlight will function
this.defaultShowErrors();
},
Please fill before submitted. when all fields are entered the error field has to disable.
You forgot to hide the error message box when there are no errors: $(".error_msge").hide() was missing
And I need to highlight the label of the radio input when nothing is selected.
You need a conditional inside the highlight and unhighlight functions that will take care of this when the element is a radio.
highlight: function (element) {
if ($(element).is(':radio')) {
$(element).siblings('label').addClass('errRed');
} else {
$(element).addClass('errRed');
}
$(element).prev('span.required-star').addClass('text-error-red').removeClass('text-error-black');
},
unhighlight: function (element) {
if ($(element).is(':radio')) {
$(element).siblings('label').removeClass('errRed');
} else {
$(element).removeClass('errRed');
}
$(element).prev('span.required-star').addClass('text-error-black').removeClass('text-error-red');
}
I also moved the code for the asterisks in here since you want them to toggle color individually.
More over I am trying to change my mandatory star from black to red.
Your CSS technique is flawed. You are trying to select everything with the "black" class and simply add a "red" class, leaving you with two classes each with a different color. Instead, you need to replace one class with the other class. Something like this...
$(".required-star").removeClass("text-error-red").addClass("text-error-black");
You need to programmatically trigger validation using the .valid() method when you use the date-picker...
$('.ipt_Field').on('change', function() {
$("#basicForm").valid();
});
You do not need the messages option. Since you are suppressing all of the messages, it's pointless.
Also do not leave the errorPlacement function empty. Put a return false inside.
errorPlacement: function() {
return false; // suppress error messages.
}
DEMO: http://jsfiddle.net/k5wxtmpL/

how to add custom error replacment messages in jquery validaiton plugin?

I would like to add custom error replacement using jquery validation plugin (http://jqueryvalidation.org/documentation/) I would like to do custom error replacement like click here
$(function() {
//simple example 1
//click event for first button
$("#form1").validate({
errorPlacement: function(error, element) {
if (element.attr("name") == "business_email" ) {
$("#bus_email").css('color',"#f42156");
$("#busp_email").removeClass("field_validation_error hidden");
$("#busp_email").addClass("field_validation_error");
}
},
rules: {
business_email: "required"
},
messages: {
business_email: "Please enter your firstname"
}
});
});
https://jsfiddle.net/fr0dc2es/7/
With this code you can get custom replacement message and act on #bus_email:
$(function() {
//simple example 1
//click event for first button
$("#form1").validate({
rules: {
business_email: "required"
},
messages: {
business_email: "Please enter your firstname"
},
errorPlacement: function(error, element) {
if (element.attr("name") == "business_email") {
$("#bus_email").css('color',"#f42156");
$("#busp_email").removeClass("hidden");
$("#busp_email").html(error);
} else {
$("#busp_email").addClass("hidden");
$("#busp_email").html();
error.insertAfter(element);
}
}
});
});
JQueryValidation Documentation
In your JSFiddle, errorPlacement function is being called and jQueryVal is working properly.
However,
Your #busp_email is shown but empty.
Your script logic is incorrect. Why do you remove a class, and add this class right after it? Why don't you hide it?
You don't need to check for every value in errorPlacement. It is not how it works. You shouldn't define a error placement for every input in a predefined error box - you should define a common placement logics by creating dynamic error messages after an input or in a specified place; or by appending an error to the specified alert; but definitely not by checking for every item.
Why default validation error placement is not suitable for you? What do you want to change? Describe it and I will try to help you - now you just provide an invalid code without any explanations.

jQuery validate not working for two fields

I need to validate that both the domain field is correct and that the placeholder field has a value. Once both are true, the Submit button will show. Using jQuery validate, I can check that the domain is correct, but its not validating the placeholder field. The playerClass rule is not being applied:
$(function() {
$("#form").validate({
rules: {
playerClass: {
required: true
}
},
submitHandler: function() {
$("body").append("<p>Validation Complete!</p>");
}
});
});
jQuery.validator.addMethod("domainChk", function(value, element, params) {
$(".submit").show();
if (this.optional(element)) return true;
var regExp = new RegExp("^(?!www\\.|http:\/\/www\.)(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\\.)+([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$");
return regExp.test(value);
},
function errmess(params, element) {
$(".submit").hide();
return "Valid hostname required for player code";
});
jQuery.validator.addClassRules({
domainChk: {
domainChk: true
}
});
jsFiddle: Link
The playerClass rule is not being applied
Your second field, with name="playerClass" is not being validated because you've applied no validation rules to it. There is no such rule called playerClass in your jsFiddle or in your OP, and you've applied no rules to the playerClass field in your jsFiddle.
Even if playerClass was a custom rule, the form is considered valid because the playerClass field is optional in your jsFiddle. Without the required rule, when the field is left blank, it's valid.
You've also failed to close your <form> element in the jsFiddle. There is no </form> tag.
EDIT:
As per documentation, any ajax() should go inside the submitHandler function within the .validate() method.
In other words, you are breaking the validation plugin with your click handler.
I need to validate that both the domain field is correct and that the placeholder field has a value. Once both are true, the Submit button will show.
Then why are you showing the submit button from within the domainChk rule? Once this rule is passed, you're showing the button with $(".submit").show().
You would typically use the .valid() method to test the form and show/hide the button.
$('input[type="text"]').on('click keyup blur', function() {
if ($('#form').valid()) {
$(".submit").show();
} else {
$(".submit").hide();
}
});
This is much closer to how it should be: http://jsfiddle.net/e04rca0t/2/

$.validator.addMethod()

I have a dropdownlist
$.validator.addMethod("ddlNames", function (value) {
if ($("#NameList.val()=="-1")
{
return false;
}
else
{
return true;
}
}, "Please select a valid Name");
This validation is going fine. But when i change the dropdown value (valid selection ) the error message occured previously its stil displayed. Please can any one help me out?
thanks
You need to call the validation programmatically when changing the drop down.
Eg. If you have: YOUR_FORM validation. Assign a variable to the validate method.
And then call that with .form() on the change event of your dropdown.
Documentation: http://jqueryvalidation.org/Validator.form/
Sample code:
$('#ddlNames').change(function() {
form_validator.form();
});
var form_validator = $("#YOUR_FORM").validate({
ignore: "",
rules: {
firstname: {
required: true,
minlength: 2
},
...
In document.ready you need to add another line that says (replace: # < targetform> with your form):
$('#<targetform>').validate({
rules : {
names : { ddlNames: true }
}
});
Make sure you have a class="required" on your <select>
You should not need to clear them yourself, but there are ways...:
$("#NameList").removeClass("error").addClass("valid");
or
$.validator.resetForm();
That will make sure you start off valid each time.

Categories

Resources