Clean previous JQuery validation error message - javascript

I have two validations for the same field and I´m using jQuery Validator, I would like to know how to clean the previous error message generated.
My problem now is that If I have the error for empty field, never is removed if I have another error like value must be higher than 10. I still showing "field must not be empty" when the value is 7.
I google on that and all suggestion are resetForm of validation.
var validator = $("#myform").validate(
);
validator.resetForm();
But of course if I do that the error message wont be showed. I just need to clean the previous error from the DOM before check for news.
Anyone knows another approach directly interacting with the DOM?
I´m trying this without success.
if ($.validator.defaults.onfocusout) {
$(element).unbind(".validate-biggerThanOrigin").bind("blur.validate-biggerThanOrigin", function () {
$(element).valid();
});
}
We´re defining the validation like this.
$.validator.addMethod("biggerThanOrigin", function (value, element, param) {
return biggerThanOrigin(value, element, param, validationMessages.biggerThanOrigin, validationMessages.referenceForkEmpty);
});
$.validator.addMethod("lessThanOrigin", function (value, element, param) {
return lessThanOrigin(value, element, param, validationMessages.lessThanOrigin, validationMessages.referenceForkEmpty);
});
Regards.

You should provide separate validation messages for errors.
$("#myform").validate({
rules: {
name: {
"required": true,
"minlength": 10
},
messages: {
name: {
required: "Please specify your name",
minlength: "Your name must be atleast 10 characters long"
}
}
});
This should work in your case.
EDIT:
Here is a working FIDDLE.

As you asked another approach , so here is the solution.
FIDDLE:
$('input').on('keyup', function () {
if ($(this).val().length == 0)
$('label').text('Field must not be empty');
else if ($(this).val() <= 10)
$('label').text('Value must be greater than 10');
else
$('label').text('');
});
This is just an example. You can use the approach.
Thanks anyway !

Related

How to display custom alert boxes in custom_func of jqgrid

I am using custom function for validating my input on edit. Following is the piece of code.
editrules:{custom: true, custom_func: customValidation}
function customValidation(val, colname) {
if (val.trim() == "") {
return [ false,"name is required " ];
} else {
return [ true, "" ];
}
}
This works fine and it displays an alert if the validation is false. I want to display my custom alert box.
I tried to use my custom alert box like
showCustomBox('ERROR', 'Name is required! ',{title : 'Error: Edit xxx grid'});
// where the function param means showCustomBox(type, message, heading);
return[false, ""];
But this displays my alert as well as the default alert. Is there a way to use oly custom alert during return? Pls suggest. Thanks in advance.
jqGrid don't provide any direct way to customize validation dialog. Nevertheless one can do make some tricks to implement what you need.
First of all one have to examine how jqGrid implements custom validation. jqGrid calls $.jgrid.checkValues to validate the input data. The method $.jgrid.checkValues calls custom_func if required (see here). Then jqGrid calls here $.jgrid.info_dialog method to display the error message. So one can for example subclass the $.jgrid.info_dialog method to display custom error message in the way like I described in the answer.
I made the demo which demonstrates the approach. The demo have custom validation in "name" column. The validation require that the saved value have to start with the text "test". I used alert to display the custom error message. Below is the main parts of the code which I used in the demo:
var useCustomDialog = false, oldInfoDialog = $.jgrid.info_dialog;
...
$.extend($.jgrid,{
info_dialog: function (caption, content, c_b, modalopt) {
if (useCustomDialog) {
// display custom dialog
useCustomDialog = false;
alert("ERROR: " + content);
} else {
return oldInfoDialog.apply (this, arguments);
}
}
});
...
$("#list").jqGrid({
...
colModel: [
{ name: "name", width: 65, editrules: {
custom: true,
custom_func: function (val, nm, valref) {
if (val.slice(0, val.length) === "test") {
return [true];
} else {
useCustomDialog = true; // use custom info_dialog!
return [false, "The name have to start with 'test' text!"];
}
} } },
...
],
...
});
As the result jqGrid could display the error message like below if one would try to save the data for "Clients" ("name") column which text don't start with "test" text

jQuery Validation validator.addMethod not being fired?

$("#attribute-save-form").validate({
debug: false,
rules: {
txtAttributeName: "*",
txtAttributeLabel: "*",
txtLength: {
NotEqualtoZero: true
}
},
messages: {
txtAttributeName: "*",
txtAttributeLabel: "*",
txtLength: {
NotEqualtoZero: "Please enter length not equal to zero"
}
},
errorElement: "span",
invalidHandler: function (form, validator) {
$(validator.errorList).each(function (index, element) {
element.message = "*";
});
////
},
errorPlacement: function (error, element) {
$(error).insertAfter(element);
}
});
$.validator.addMethod("NotEqualtoZero", function (value, element, param) {
return this.optional(element) || /[^0]/.test(value);
}, "Not Equal to zero.");
});
I don't know what mistake I'm making or what I'm missing but it is just displaying * error message and not the "not equal to zero". Please tell me what I'm doing wrong
Update: I want to check that text value of text box is not equal to 0
i have debugg it the problem is in element my element "txtLength" is not coming
invalidHandler: function (form, validator) {
$(validator.errorList).each(function (index, element) {
element.message = "*";
my function "NotEqualToZero" is basically not being called here , am i missing somethig like i have include this in start
<script src="~/Scripts/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.extend(jQuery.validator.messages, {
required: "*"
});
is there anything else i have to include
Your NotEqualtoZero rule is working perfectly fine and showing the "Please enter length not equal to zero" error in this simple demo. Just enter 0 into the text box, click enter, and the error message appears: http://jsfiddle.net/tr22y/
However NotEqualtoZero is optional unless you also specify the required rule. In other words, there will be no error messages if you leave it blank.
The rest of your rules, however, do not make any sense at all.
rules: {
txtAttributeName: "*", // <- "*" is nonsense here
txtAttributeLabel: "*", // <- "*" is nonsense here
txtLength: {
NotEqualtoZero: true
}
},
There is no such rule as *. You have to enter the name of a single valid rule or key:value pairs of multiple valid rules.
Even so, that mistake still does not break anything. I cannot see your HTML markup, nor can I know which rules you need, but with your present jQuery code, the NotEqualtoZero rule still works perfectly as designed...
DEMO: http://jsfiddle.net/tr22y/2/
EDIT: After cleaning up the code in your question, you can also see that you have an extra }); at the very end. Perhaps you forgot the $(document).ready(function() { line from the top? Maybe a cut & paste mistake when you posted the question?
The above code works fine , my mistake was that i was giving element ids instead of element names in rules and messages in validate method, that's why add method was not calling.

jQuery validate - specify only errorPlacement

I'm having difficulty getting error placement to work. I have a series of forms on my page, each using the built-in validation classes—required, number, etc—but for some reason the error placement isn't working. At all.
The rest of the form validation works great, but I'm not getting my alert to show.
$(".bundle-forms-form-container form").validate({
errorPlacement: function(error, element) {
alert("X");
var customTarget = $(element).closest("form").find(".errorHere");
if (true || customTarget.length)
customTarget.html(error);
//else
error.insertAfter(element);
}
});
It looks like the problem is that jQuery validate loses its mind if you call validate on a result set with multiple forms. The solution is simple
$(".bundle-forms-form-container form").each(function(i, el){
$(el).validate({
errorPlacement: function(error, element) {
var customTarget = $(element).closest("form").find(".errorHere");
if (customTarget.length)
customTarget.empty().append(error);
else
error.insertAfter(element);
}
});
});

POST via ajax only if validation check returns true

I'm checking my form with RSV validator. Want to get work following: Let's say user opened page for the first time. After filling all text input boxes, when user clicks #submit_btn FOR THE FIRST TIME, the form submit function fires RSV (validator), validator checks if there is any error. If all right, posts data via ajax, else RSV shows error messages array with the help of alert(). THIS PROCEDURE ONLY FOR THE FIRST TIME
BTW: RSV - validator. If no error occured during validation process the myoncomplete() function returns 1.. If something went wrong it alerts. Got from here
I can't get it work. Please help me to fix logic/code mistakes. Thx in advance
My JS
var int=null;
var counter=0;
function myOnComplete() {
return 1;
}
$(document).ready(function () {
$("#add_form").RSV({
onCompleteHandler: myOnComplete,
rules: [
"required,name,Page name required",
"required,title,Page title required.",
]
});
$("#add_form").submit(function (e) {
e.preventDefault();
dataString = $("#add_form").serialize();
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
//do something if ajax call is success
int = setInterval(call, 3000);
var message = result.msg;
var err = result.err;
if (message != null) {
$.notifyBar({
cls: "success",
html: message
});
}
if (err != null) {
$.notifyBar({
cls: "error",
html: err
});
}
},
error: function (e) {
//ajax call failed
alert(e);
}
});
});
$("#submit_btn").click(function () {
if(counter===0){
if(myOnComplete()===1) $('#add_form').submit();
else return false;
}
else $('#add_form').submit();
counter++;
});
$('#autosave').click(function(){
if($(this).is(':checked')){
int = setInterval(call, 3000);
$('#submit_btn').attr({'value':'Save&Exit'});
}
else{
$('#submit_btn').attr({'value':'Save'});
clearInterval(int);
}
});
});
function call() {
$('#add_form').submit();
}
Looking through the RSV code it looks like whatever you attach RSV to has its submit rebound to validate the data using .RSV.validate()
As seen here:
$(this).bind('submit', {currForm: this, options: options}, $(this).RSV.validate);
});
Which means that if you use .submit() you are calling .RSV.validate also.
So once you validate the info try binding your submit to the standard submit function.
Edit: To help explain
When you use
$("#add_form").RSV({...});
The RSV javascript code is binding .RSV.validate() to the submit event of your add_form element. Meaning when you submit your add_form form .RSV.validate() is being called before the submit.
Try running the script code below with and without the .RSV() call
This script will log ALL handlers for ALL events on the add_form element. You notice that calling $element.RSV({...}) attaches a second event handler to the submit event of the add_form element. I am unsure of the best way to access this event handler to .unbind() it. Good luck :)
jQuery.each($('#add_form').data('events'), function(i, event){
jQuery.each(event, function(i, handler){
console.log(handler);
});
});
OK, to my understanding now you only want to validate the first set of data and if that validates correctly trust the user, i got this working on jsFiddle with an easy example, i guess you can make use of that
http://jsfiddle.net/WqnYa/9/
Basically what i do is that i catch the submit button click and not the forms submit function, maybe it can be done that way, too. I assign a class "needsvalidation" and when ever the first validation passes, i simply remove that class. And if that class is not present, the validation will not be initialized due to $(this).hasClass('needval')
If that's not what you're looking for then your question needs way more clarity :( hope this helps though!

improve my jquery validation plugin code

Just hoping soemone can help me to write better code than I can come up with on my own.
I am using the jquery validation plugin. I have some fields that are mandatory ONLY if certain options are chosen.
The below code works fine. But the thing is, is that that my list of 'OR's is much longer than I've put here. and it needs to be applied not just to 'directorsName' but a whole long list of inputs, selects etc.
My question is.. how can I wrap up the code contained inside the RETURN?
(so I dont have to keep repeating my 'OR's. I'm guessign I need a function but I'm unsure of the syntax)
$("#myForm").validate({
rules: {
directorsName : {
required: function(element) {
return ( $('#account_for').val() == "Joint" || $('#directors_number').val() == "2" || $('#directors_number').val() == "3" );
}
}
}
});
Thanks in advance
Here's a code snippet for a custom validator. You can apply this same syntax to your own custom validation needs.
$.validator.addMethod("noanon", function(value) {
return value.toLowerCase().indexOf("anonymous") != 0;
}, 'Do not hide behind the cover of anonymity')
You can then use it just like any of the built-in validation rules like:
name: {
required: true,
minlength: 2,
noanon: true
},
If you have not already read it, I suggest reading the 3-part blog that this code comes from over at coldFusion Jedi.
You can do this, which is supported cross browser using $.inArray():
$("#myForm").validate({
rules: {
directorsName : {
required: function(element) {
return $('#account_for').val() == "Joint" ||
$.inArray($('#directors_number').val(), ['2','3']);
}
}
}
});
list = ['1', '2', '3', '...'];
return $('#account_for').val() == "Joint" || list.indexOf($('#directors_number').val()) != -1;

Categories

Resources