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);
}
});
});
Related
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 !
I am using jQuery validator plugin with Bootstrap 3 to validate my form inputs. It works great but when user enters any wrong input the alignment gets messed up.
Screenshots
Before: http://oi58.tinypic.com/23sta4p.jpg
After: http://oi59.tinypic.com/2pq17a8.jpg
How can I fix it?
Try adding some custom valdiation display fro Jquery validation
This is the solution you need, you can use the errorPlacement method to override where to put the error message
$("form").validate({
highlight: function(e) {
$(e).closest(".form-group").addClass("has-error")
},
unhighlight: function(e) {
$(e).closest(".form-group").removeClass("has-error")
},
errorElement: "span",
errorClass: "help-block",
errorPlacement: function(e, t) {
if (t.parent(".input-group").length) {
e.insertAfter(t.parent())
} else {
e.insertAfter(t)
}
}
})
});
$("#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.
I am using jquery.validate to check my form for errors and I am trying to get the id of the element that has raised an error.
Here is my basic working code, hopefully it should be clear from this what I am after:
function customError(){
alert("this is where I want the element ID");
}
function submitForm($form){
$form.validate({
required: customError(),
errorPlacement: function(error, element) {},
submitHandler: function(){
alert("submited");
}
});
}
...
errorPlacement: function (error, element) {
customError(element.attr('id'));
},
...
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!