How to use jQuery Validate's errorPlacement and showErrors simultaneously - javascript

I recently removed the messages function from my validation. I then placed in jQuery validate's showErrors function so that I could get the borders for the required inputs to change to red. At this point, everything was working well until I added showErrors with it.
The reason for adding showErrors is that I wanted a simple message to appear, instead of multiple, and the borders to still show as red.
From my snippet below, you will see that only showErrors is currently working. Is there anyway to get both of these to work simultaneously. If so, how?
Alternatively, here is a jsfiddle
Adjusted JS
errorPlacement: function() {
return false;
},
showErrors: function(errorMap, errorList) {
$('#formErrors').html('All fields must be completed before you submit the form.');
this.defaultShowErrors();
},
submitHandler: function() {
submit();
},
$('#catalogRequestForm').validate({
ignore: [],
rules: {
first_name: {
required: true,
minlength: 2
},
last_name: {
required: true,
minlength: 2
},
address1: {
required: true,
minlength: 5
},
city: {
required: true,
minlength: 2
},
state: {
required: true
},
zip: {
required: true,
digits: true,
minlength: 5
},
email: {
required: true,
email: true
}
},
errorPlacement: function(){
return false;
},
showErrors: function(errorMap, errorList) {
$('#formErrors').html('All fields must be completed before you submit the form.');
},
submitHandler: function() {
submit();
},
});
.error {
border: 2px solid #b82222;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<form method="POST" id="catalogRequestForm">
<input type="text" name="first_name" placeholder="First Name *">
<input type="text" name="last_name" placeholder="Last Name *">
<div id="formErrors"></div>
<input id="requestSubmit" type="submit" value="Submit">
</form>

Use this.defaultShowErrors() within showErrors to reactivate the default message behavior. Since you have a return false within errorPlacement, you only see your styling and not the messages.
showErrors: function(errorMap, errorList) { // <- disable default errorPlacement
$('#formErrors').html('All fields must be completed before you submit the form.');
this.defaultShowErrors(); // <- re-enable default errorPlacement
},
Read more: jqueryvalidation.org/validate/#showerrors
By only containing submit(), your submitHandler is completely broken. If that is your real function, then remove the submitHandler entirely because a regular form submit is already the default behavior. Otherwise, if you're doing something before the submit, then you'll need to pass a form argument and attach it to .submit().
submitHandler: function(form) { // <- pass 'form' argument into function
// do something, then submit
form.submit(); // <- attach 'form' argument to '.submit()'
}
DEMO:
$('#catalogRequestForm').validate({
ignore: [],
rules: {
first_name: {
required: true,
minlength: 2
},
last_name: {
required: true,
minlength: 2
}
},
errorPlacement: function() {
return false;
},
showErrors: function(errorMap, errorList) {
$('#formErrors').html('All fields must be completed before you submit the form.');
this.defaultShowErrors();
},
submitHandler: function(form) {
form.submit();
},
});
.error {
border: 2px solid #b82222;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<form method="POST" id="catalogRequestForm">
<input type="text" name="first_name" placeholder="First Name *">
<input type="text" name="last_name" placeholder="Last Name *">
<div id="formErrors"></div>
<input id="requestSubmit" type="submit" value="Submit">
</form>
jsFiddle version: jsfiddle.net/ryoufcqh/

Related

check another validation rules after validating blank field

I need to validate another ready made bad words filter after validating first rules (blank fields). I have all codes in ready made, someone please help me to add this second validation in my page.
This is my jquery codes where I need to include the 2nd validation.
$(function() {
$("#review").focus(function() {
$("#comments").removeClass('hide')
});
$("#sky-form").validate({
rules: {
digits: {
required: true,
digits: true
},
name: {
required: true
}
},
messages: {
digits: {
required: 'Please enter a valid amount of Money'
},
name: {
required: 'Please enter your username',
}
},
submitHandler: function(g) {
$(g).ajaxSubmit({
beforeSend: function() {
$('#sky-form button[type="submit"]').attr('disabled', true)
},
success: function() {success funtion goes here}
This is the 2nd validation codes that I need to include on top. Mainly I need this function - bwords=badwords(textbox_val); - It will verify bad word's after blank fields is okay.
<script language="javascript" type="text/javascript">
function Message()
{
var textbox_val=document.form.textbox.value;
if(textbox_val=="")
{
alert("Please enter a message");
return false;
}
bwords=badwords(textbox_val);
if(bwords>0)
{
alert("Your message contains inappropriate words. Please clean up your message.");
document.form.textbox.focus();
return false;
}
}
</script>
Those both function is working but I just need to include both validation like 2nd one in the top first script.
Sorry for my bad Enlgish.
You can add a new rule in your code. I called this rule badWords and for me the
bad word is BAD so when you try to type BAD in the name field you will get the
validation error message.
$.validator.addMethod("badWords", function(value, element) {
if (value.trim().length == 0) {
return false;
}
if (value == 'BAD') {
return false;
}
return true;
}, "BAD WORD");
$(function () {
$("#sky-form").validate({
rules: {
digits: {
required: true,
digits: true
},
name: {
required: true,
badWords: true
}
},
messages: {
digits: {
required: 'Please enter a valid amount of Money'
},
name: {
required: 'Please enter your username',
}
}
});
});
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>
<form id="sky-form">
<label for="ele1">Digits:</label>
<input type="text" id="ele1" name="digits"/>
<br/>
<label for="ele2">Name:</label>
<input type="text" id="ele2" name="name"/>
<br/>
<input type="submit" id="submit"/>
</form>

How to highlight validation jQuery

I'd love some help over here since I'm a rookie when it comes to jQuery.
I have this code right here:
$(document).ready(function(){
$("#subscribe").validate({
debug: false,
rules: {
email: {
required: true,
email: true
}
},
messages: {
email: "*",
},
submitHandler: function(form) {
$.post('wp-content/themes/abc/process.php', $("#subscribe").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
Now, what im trying to do is to replace the message: * , with a highlight of the input field. So instead of showing the message * right after my e-mail input field, i'd like to add a class to my e-mail input field. Help would be much appreciated.
As victor k and Cory mentioned, jQuery validate adds a .error class to the element being validated if it doesn't pass the validation rules. It also adds a default message. If you want to remove the message and highlight the input field, you can set the message to the empty string and highlight the input field with CSS. Here's an example:
$(document).ready(function() {
$("#subscribe").validate({
debug: false,
rules: {
email: {
required: true,
email: true
}
},
messages: {
email: "",
},
submitHandler: function(form) {
$.post('wp-content/themes/abc/process.php', $("#subscribe").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
#email.error {
border: 2px solid red;
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<form id="subscribe">
<input type="text" id="email" name="email">
</form>

jQuery validation not validating onkeyup

Can someone help me understand why onkeyup validation is not working? I have been staring at it too long! Thanks.
JSFiddle here.
Code:
$(document).ready(function () {
jQuery('#DSH0000000146FF').validate({
rules: {
dish_name: {
required: true
},
dish_description: {
required: true
}
},
messages: {
dish_name: {
required: "Please enter a name, no longer than 80 characters."
},
dish_description: {
required: "Please enter a description, no longer than 240 characters."
}
},
submitHandler: function (form) {
if(jQuery('#DSH0000000146FF').validate()){
alert("SUBMITTED!");
}
else{
}
}
});
});
Add submit button to form
<textarea id="DSH0000000146d" name="dish_description"
class="textarea-comment dish_description" maxlength="240">More testing
</textarea><br/>
<input type="submit"></input> <!-- Add this line -->
jsfiddle

jQuery validation errorPlacement - can't remove error once corrected

hoping you can help me out! I'm having trouble removing an error once the user has corrected their error. For example, validating an email field. every character press keeps appending an error as many times as necessary until it's validated. Here is a snippet:
$( "#bookings" ).validate({
rules: {
email: {
required: true,
email: true
},
message: {
email: {
required: "field is required",
email: "invalid email"
},
errorLabelContainer: $("ul", $('div#results')), wrapper: 'li',
errorContainer: $('div#results'),
errorPlacement: function(error, element) {
$('#results').append(error);
}
success: function(error){
error.remove();
}
});
<div id="results">
</div>
<form name="bookings" id="bookings" method="post" action="#">
<div class="item" style="clear:left;">
<label>E Mail *</label>
<input id="femail" name="email" type="text">
</div>
</form>
What I want to achieve is for the error to appear ONCE.So far I have successful removal. but the error keeps appending itself over and over again until validation is successful.
Try this out:- http://jsfiddle.net/adiioo7/hGNRG/
JS:-
$("#bookings").validate({
rules: {
email: {
required: true,
email: true
},
message: {
email: {
required: "field is required",
email: "invalid email"
},
errorLabelContainer: $("ul", $('div#results')), wrapper: 'li',
errorContainer: $('div#results'),
errorPlacement: function (error, element) {
$('#results').append(error);
},
success: function (error) {
error.remove();
}
}
}
});
Get rid of your errorLabelContainer,wrapper,errorContainer,errorPlacement, and success options and put this instead:
wrapper: 'li',
errorLabelContainer:$('#results')
The stuff you had is basically duplicating (poorly) what the Validation plugin does by default.
See it working here: http://jsfiddle.net/hGNRG/1/ (hat tip to #wiz-kid for creating the fiddle).

jQuery Validation plugin with CKEditor

I know this question has been asked before and I have read all the previous questions and I still can't get the jQuery validator to properly validate CKEditor fields.
My form is below:
<form id="faq-form">
<p>
<label>Title:</label>
<input type="text" id="faq-title" name="faq-title" class="faq-title" />
</p>
<p>
<label for="question">Question:</label>
<textarea name="question" id="question"></textarea>
</p>
<p>
<label for="answer">Answer:</label>
<textarea name="answer" id="answer"></textarea>
</p>
<p>
<input id="submit-faq" name="submit-faq" type="submit" value="Submit" />
</p>
</form>
Both textareas are converted to CKEditor fields using:
<script>
CKEDITOR.replace('question', { toolbar : 'forum' });
CKEDITOR.replace('answer', { toolbar : 'forum' });
</script>
When I try to validate, only the title field gets validated. I am not sure what I am doing wrong. Here is my javascript code for validating (the following sits in a jQuery document ready function).
$('#faq-form').submit(function() {
// Update textareas with ckeditor content
for (var i in CKEDITOR.instances) {
CKEDITOR.instances[i].updateElement();
$.trim($('#' + i).val());
}
// Validate the form
if ( ! $('#faq-form').validate({
rules: {
'faq-title': {
required: true,
minlength: 5
},
answer: {
required: true,
minlength: 20
},
question: {
required: true,
minlength: 20
}
}
}).form()) {
console.log('Form errors');
return false;
}
Once the validation is complete, I will use a $.post method instead of a normal form get or post so I can update my page without reloading. The $.post comes after the validation method but I didn't think it was necessary to show.
I was finally able to get it working. CKEditor hides the textareas when it runs and the jQuery validator ignores hidden elements. In the validate function, this can be changed. So my new code is below:
if ( ! $('#faq-form').validate({
ignore: "input:hidden:not(input:hidden.required)",
rules: {
'faq-title': {
required: true,
minlength: 5
},
answer: {
required: true,
minlength: 20
},
question: {
required: true,
minlength: 20
}
},
messages: {
'faq-title': {
required: "The title field is required"
},
answer: {
required: "The answer field is required"
},
question: {
required: "The question field is required."
}
},
errorElement: "span",
errorPlacement: function (error, element) {
error.appendTo(element.prev());
}
}).form()) {
console.log('Form errors');
return false;
}
I also added messages and modified the element and location of the errors when they are displayed. I figured that might be helpful to anyone else who stumbles across this.
Ok lets cut it down, I have spent hours to get the error message of CKEditor in the right place, because every time it showing up on top of the CKEditor or just after the label which is not look nice.
As CKEditor hides the textarea and put its span tag right after the textarea. Please use browser tool to inspect the dom elements, then you can see the textarea is hidden.
I just adjusted the code to get the error message label/span just under the CKEditor.
$('#messageForm').validate(
{
ignore: 'input:hidden:not(input:hidden.required)',
rules: {
msgTitle: {
minlength: 2,
required: true
},
msgText: {
minlength: 2,
required: true
}
},
errorElement: "span", // can be 'label'
errorPlacement: function (error, element) {
if ($(element).attr('id') == 'msgText') {
$('#cke_msgText').after(error);
} else {
element.after(error);
}
},
highlight: function (element) {
$(element).closest('.form-group').removeClass('text-success').addClass('error');
},
success: function (element) {
element
.closest('.form-group').removeClass('error').addClass('text-success');
}
});
Here, 'msgText' is the id of the textarea which is hidden, and cke_msgText id of the ckeditor, you can find the id by inspecting the dom element, perhaps ckeditor takes the id attribute of textarea and prefix 'cke_' with it.
My guess is that CKEditor doesn't play nicely with validation, at least by default. You'd need to remove the editors before validation (CKEditor works by hiding the thing being edited and then inserting an iframe and sticking the editable content in there; when you remove the editor it shuts down the iframe and copies over the content -- at least that's from memory). My guess is that if you inspect the DOM you'll see that the content of the textareas isn't changing.
You may find NicEdit more useful in this context -- see this thread:
https://stackoverflow.com/questions/3914510/wysiwyg-editor-without-iframe
Your code:
$('#faq-form').submit(function() {
// Update textareas with ckeditor content
for (var i in CKEDITOR.instances) {
CKEDITOR.instances[i].updateElement();
$.trim($('#' + i).val());
}
if ( ! $('#faq-form').validate({
rules: {
'faq-title': {
required: true,
minlength: 5
},
answer: {
required: true,
minlength: 20
},
question: {
required: true,
minlength: 20
}
}
}).form()) {
console.log('Form errors');
return false;
}
....
You should not use .validate() inside a conditional. That's what the .valid() method is for. .validate() is only used for initializing the plugin once on DOM ready with your rules & options. Once initialized, then .valid() can be used inside conditionals to trigger a test and return a boolean.
Also, you should not have .validate() inside of submit handler. The plugin has it's own submitHandler callback function.
Your code should be changed into something like:
$(document).ready(function() {
$('#faq-form').validate({ // initialize the plugin
// rules & options,
rules: {
'faq-title': {
required: true,
minlength: 5
},
answer: {
required: true,
minlength: 20
},
question: {
required: true,
minlength: 20
}
},
submitHandler: function (form) {
// Update textareas with ckeditor content
for (var i in CKEDITOR.instances) {
CKEDITOR.instances[i].updateElement();
$.trim($('#' + i).val());
}
}
})
if ( ! $('#faq-form').valid() ) { // test the form for validity
console.log('Form errors');
return false;
}
});
Best solution I found so far, simple and elegant:
$('#form1').validate({
ignore: [],
rules: {
corpo : {
required: function()
{
CKEDITOR.instances.corpo.updateElement();
}
}
}
})
Font: http://devlog.waltercruz.com/usando-ckeditor-e-jquery-validate-juntos
<form>
<textarea class="ckeditor" id="noticeMessage" name="message"></textarea>
</form>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<form>
<textarea class="ckeditor" id="noticeMessage" name="message"></textarea>
</form>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
$("form").submit( function() {
var messageLength = CKEDITOR.instances['noticeMessage'].getData().replace(/<[^>]*>/gi, '').length;
if( !messageLength ) {
alert( 'Please enter a message' );
}
}
</script>
see for full reference
----------------------
http://christierney.com/2012/12/14/ckeditor-4-required-field-validation/

Categories