I have a text area which I've used ckeditor on:
<form name="product_edit" action="products.php" method="post" id="edit_form" enctype="multipart/form-data">
<textarea name="products_description" wrap="soft" cols="75%" rows="20" id="products_description"></textarea>
Also after including jQuery I have the following to validate the form:
$(document).ready(function() {
$('#edit_form').submit(function() {
if ($('#products_description').val() == '') {
alert('Please include a product description.');
return false;
}
}); // end submit()
}); // end ready()
I also have a couple of other fields I validate which aren't included for brevity.
My problem is that while all the other fields work fine with that, the text area sometimes doesn't. If I type stuff in it sometimes doesn't recognize it and still pops up the alert. Then if I go back and click (I don't even have to type anything more) and try to submit it works.
Any guesses as to why?
Is this still an issue? If not, post your solution.
CKEeditor does not work like that, you don't get data like $('#products_description').val(). CKEditor doesn't use the textarea directly, it generates an iframe to use instead of it. To get the value, call CKEDITOR.instances.editor1.getData() where editor1 in your case might be products_description.
This worked for me while no description is added works fine but if you put some space it is considered as content.Please add required attribute for your textarea.
Please include jquery validator and jquery library.
$(document).ready(function() {
$('#edit_form').validate({
ignore: [],
rules: {
products_description: {
required: function()
{
CKEDITOR.instances.products_description.updateElement();
}
}
},
messages: {
products_description: "مطلوب"
},
/* use below section if required to place the error*/
errorPlacement: function(error, element)
{
if (element.attr("name") == "products_description")
{
error.insertAfter("#cke_description");
} else {
error.insertAfter(element);
}
}
});
});
Related
I am pretty new to jquery validate so there is hopefully a simple answer to my problem!
I got a form with a textarea and i want to do a simple validation (required). The validation works fine for the simple text fields but it does not work for the text area...
I got the following code to initialize jq validate.
note hat my textarea has the both the id and name attributes set to "post_content".
/**
*
*/
this.account_validator = $("form#profile_form").validate({
rules: {
post_content : "required",
errorPlacement: function(label, element) {
if (element.is("textarea")) {
label.insertAfter(element.next());
} else {
$(element).closest('div').append(label);
}
}
}
});
If my "post_content" is ==""and I add the following alert popup I get the following
alert(this.account_validator.form()); --> true
alert(this.account_validator.element("#post_content")); --> false
alert(this.account_validator.form()); --> true
As far as I understand the .element method on the validator object should add that element for validation so the second call to the form() method should also return false...
BTW, if my "post_content" is !="" and I add the following alert popup I get the following
alert(this.account_validator.form()); --> true
alert(this.account_validator.element("#post_content")); --> true
alert(this.account_validator.form()); --> true
Thanks,
Christian
I'm using the bootstrap validator plugin to valid my form client side and it seems to fail when revalidating a summernote textarea. It validates the first time, but when the text is updated the validation doesn't update.
Here's the validation (snipped out other validation fields)
function validateEditor() {
// Revalidate the content when its value is changed by Summernote
$('#application-form').bootstrapValidator('revalidateField', 'application'));
};
$('.application-form')
.bootstrapValidator({
excluded: [':disabled'],
fields: {
application: {
validators: {
callback: {
message: 'Please do not leave this blank.',
callback: function(value, validator) {
var code = $('[name="application"]').code();
// <p><br></p> is code generated by Summernote for empty content
return (code !== '' && code !== '<p><br></p>');
}
}
}
}
}
}).on('success.form.bv', function(e) {
e.preventDefault();
console.log('Form successfully validated.');
})
.find('[name="application"]')
.summernote({
height: 400,
onkeyup: function() {
validateEditor(); // Revalidate form onkeyup
},
onpaste: function() {
validateEditor(); // Revalidate form on paste
},
});
Here's the markup (again snipped from other fields)
<div class="form-group">
<textarea name="application"></textarea>
</div>
This is a huge issue because if the textarea is left blank the first time, the form can never be resubmitted since the validation doesn't update when the error is fixed by the user.
I had the same problem, but with FormValidation.io, which is a very similar plugin.
Solution : My textarea had the required attribute. I removed it and bam, problem solved.
Now, I'm genuinely sorry if this isn't a direct solution to your problem, your code obviously doesn't have the required attribute, but I just thought I'd share with other people still, because this was driving me nuts for hours and this was the most relevant post about this problem on here.
That is all.
Got a quick question about a form validation using jQuery. So I have huge-butt form, which is validated and submitted properly. The only problem I keep running into is that when I try to submit it, and the form is invalid, the window does not scroll to the invalid field. It tries to - the view sort of jumps about half an inch above the submit button and that's it - the invalid field is not actually shown on the page. In terms of the jQuery default settings on the validator, I have the following code:
$.extend($.validator, {
defaults: {
messages: {},
groups: {},
rules: {},
errorClass: "error",
validClass: "valid",
errorElement: "label",
focusInvalid: true,
errorContainer: $([]),
errorLabelContainer: $([]),
onsubmit: true,
ignore: ":hidden",
ignoreTitle: false,
}
When the validator runs, this is the focusInvalid() function definition:
focusInvalid: function() {
if ( this.settings.focusInvalid ) {
try {
$(this.findLastActive() || this.errorList.length && this.errorList[0].element || [])
.filter(":visible")
.focus()
// manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
.trigger("focusin");
} catch(e) {
// ignore IE throwing errors when focusing hidden elements
}
}
},
Finally, on form validation:
if ( validator.form() ) {
if ( validator.pendingRequest ) {
validator.formSubmitted = true;
return false;
}
return handle();
} else {
validator.focusInvalid();
return false;
}
focus isn't the correct function for scrolling the page to a particular element. You need scrollTop, or a similar function. There are several questions about this, I like this answer which includes a simple example, and even includes the alternative solution with animation.
Thanks guys! It was fixed by having the script add custom classes to the invalid forms and focusing on them. We tried scrollTop, but that didn't work at all, so we went with a focus scenario. The invalidHandler function code is below for anyone who's interested:
// invalidHandler to set focus to invalid controls
invalidHandler: function(event, validator) {
var $invalidElement = $(validator.errorList[0].element);
if ($invalidElement.hasClass('chosen-select')) {
$invalidElement.trigger('chosen:activate');
} else if ($invalidElement.siblings('ul.token-input-list').length > 0) {
var $inputToken = $invalidElement.siblings('ul.token-input-list').find('input');
$inputToken.focus();
}
}
I am trying to clear all error messages as well error highlighting when user click on the clear form button, below are actual requirements
Validate form using Jquery validation
When user click on a field error message should be cleared (per field)
On clicking reset button, every error should be cleared
here is my code
$( document ).ready(function(){
var validator = $("#register_form").validate({
validator.resetForm();
focusCleanup: true,
rules: {
// custom rules
},
messages: {
// custom messages
}
});
For me, first 2 things are working, but when I am trying to clear complete form, I am not able to do this.this is how I am trying to clear it
function clearInputForm(){
alert("");
var validator1 = $( "#register_form" ).validate();
validator1.resetForm();
$("#register_form")[0].reset();
}
But nothing is happening , though with $("#register_form")[0].reset();, form fields are getting clear, but error messages are not getting cleared.
Quote OP:
1) Validate form using Jquery validation
You cannot put the validator.resetForm(); method inside of the .validate() method.
.validate() is a plugin method where the only thing that can go inside is a comma separated map of the allowed options, {option:value, option:value, etc.}, as per the .validate() method documentation.
resetForm() method documentation
$("#register_form").validate({
rules: {
firstname: {
required: true
},
lastname: {
required: true
},
cell: {
required: true
}
},
messages: {
// custom messages
}
});
.validate() method DEMO: http://jsfiddle.net/P46gL/
Quote OP:
2) When user click on a field error message should be cleared (per field)
This is thanks to the focusCleanup option. As you've already done, set it to true and when you click on the field with an error, the error clears.
$("#register_form").validate({
focusCleanup: true,
rules: {
....
focusCleanup DEMO: http://jsfiddle.net/P46gL/1/
Quote OP:
3) On clicking reset button, every error should be cleared
You would call the resetForm() method from within a click handler of the reset button. This will immediately remove all error messages from the entire form and reset the validation plugin to its initial state.
$('#clearform').on('click', function () {
$("#register_form").validate().resetForm(); // clear out the validation errors
});
Make sure the reset button is type="button" or type="reset" or it will trigger validation.
<input type="reset" id="clearform" value="reset form" />
Clear Errors DEMO: http://jsfiddle.net/P46gL/3/
Clearing out the field data
You can clear out the values of the fields by calling a JavaScript .reset() like this.
$('#clearform').on('click', function () {
var form = $("#register_form");
form.validate().resetForm(); // clear out the validation errors
form[0].reset(); // clear out the form data
});
Full Working DEMO: http://jsfiddle.net/P46gL/4/
$("#register_form")[0].reset();, form fields are getting clear, but error messages are not getting cleared.
to do this you can put one more line below it:
function clearInputForm(){
alert("");
var validator1 = $( "#register_form" ).validate();
validator1.resetForm();
$("#register_form")[0].reset();
$('.error').hide();
}
Although you should do this way:
$( document ).ready(function(){
var validator = $("#register_form").validate({
focusCleanup: true,
rules: {
// custom rules
},
messages: {
// custom messages
}
});
$('[type="reset"]').on('click', function(){
validator.resetForm();
});
});
You should put your validator.resetForm(); in the click event of reset button.
If nothing works then try this approach (specially for clearing data purpose):
1- Form html:
<input type='reset' class="button_grey resetForm" value='Reset'>
2- Jquery validate
// you can add error fields
var validator = $("#clearform").validate({
focusCleanup: true
});
3- Reset the form
$('[type="reset"]').on('click', function(){
$("#clearform").closest('form').find("input[type=text], textarea").val("");
$('input:checkbox').removeAttr('checked');
validator.resetForm();
return false;
});
All error messages will be cleared
$('.btn-reset').on('click', function () {
$( "label.error" ).remove();
});
I am planning on showing/hiding divs to validate a form.
But the divs only show a split second, and then the form gets submitted...
Any ideas why?
here is the code:
function validateForm() {
var name = nameEmpty(document.getElementById("annonsera_name"));
if (nameEmpty(name)){return false;}
return false;
}
function nameEmpty(fld){
if (fld.value==0) {
document.getElementById("annonsera_nameempty_error").style.display='block';
document.getElementById("annonsera_namenotvalid_error").style.display='none';
document.getElementById("annonsera_name").focus();
return false;
}
else if (fld.value.match(alphaExp)) {
document.getElementById("annonsera_namenotvalid_error").style.display='block';
document.getElementById("annonsera_name").focus();
document.getElementById("annonsera_nameempty_error").style.display='none';
return false;
}
document.getElementById("annonsera_nameempty_error").style.display='none';
document.getElementById("annonsera_namenotvalid_error").style.display='none';
return false;
}
and here is the form:
<form name="annonsera" id="annonsera" method="post" enctype="multipart/form-data" onSubmit="return validateForm();">
It's probably generating an error and therefore never returning anything. Assuming you are using Firefox, have you checked the javascript console?
I see what looks like a problem here, where you call nameEmpty() twice - once with a field, and the other time with a (presumably?) boolean value:
var name = nameEmpty(document.getElementById("annonsera_name")); // Returns boolean
if (nameEmpty(name)){return false;} // Tries to pass boolean back into nameEmpty?
Maybe a bit offtopic, but here goes...
You should really consider JQuery Validation, it's nice, clean and easy to implement. I've done it a few times, and never looked back since. It sure beats the manual validation method like the one you use :)
Check out the example, there really is not that much code to write, to get validation going.
In your example that would be (not tested):
<script>
$(document).ready(function(){
$("#annonsera").validate({
rules: {
annonsera_name: {
required: true,
minlength: 1
}
},
messages: {
annonsera_name: {
required: "You need to write your name",
minlength: jQuery.format("At least {0} characters required!")
}
}
})
});
</script>
There are also a lot of ways of customization through dhtml and css, check out the options.