I need to put a promotional message either at the bottom of the form or in an alert when a user meets certain criteria. I think an alert might be best. It's to do with certain postcodes so I will need to write a regex (I haven't done this yet). It needs to happen when the user clicks submit and before it goes to the server. I'm not sure how to write this and where it should be placed in my script. This is what I have so far if it helps.
$(document).ready(function(){
$("#orderForm").validate({
onfocusout: function(element) {
this.element(element);
},
rules: {
shipFirstName: {
required: true,
},
shipFamilyName: {
required: true,
},
shipPhoneNumber: {
required: true,
},
shipStreetName: {
required: true,
},
shipCity: {
required: true,
},
billEmailAddress: {
required: true,
},
billPhoneNumber: {
required: true,
},
billCardNumber: {
required: true,
},
billCardType: {
required: true,
},
shipPostalCode: {
postalCode: true,
},
fidelityCardNumber: {
creditCardNumber: true,
},
}, //end of rules
}); // end of validate
}); // end of function
$.validator.addMethod('postalCode',
function (value, element)
{
return this.optional(element) || /^[A-Z]{2}\d{1,2}\s\d{1,2}[A-Z]{2}$/.test(value);
}, 'Please enter a valid Postal Code');
$.validator.addMethod('creditCardNumber',
function(value, element)
{
return this.optional(element) || /^[A-Z]{1}([A-Z]|\d){4}\s?([A-Z]|\d){5}\s?([A-Z]|\d){3}\d{1}(\!|\&|\#|\?){1}$/.test(value);
}, 'Please enter a valid card number');
You should be able to do something like this (this will replace the default submit behavior):
$("#orderForm").validate({
submitHandler: function(form) {
// code to display personal message
// code to handle form submission
},
onfocusout: function(element) {
...
Write a click function for submit button and call ajax function in that
$("#submit").click(function(){
alert("This is a promotional message on submit");
//here write ur ajax code.
});
ajax in Jquery.
You need to provide a submitHandler as an option to the validate method.
submitHandler: function(form) {
if ($("form #hasAsked").val() != 'true' && /[MK]{2}[1-15|17|19|77]{2}/.test($("#shipPostalCode").val()) {
openModalDialog();
return false;
}
return true;
},
...
An a function
function openModalDialog() {
$("<div>Wanna buy?? <button value="yes" id="y/><button value="no" id="n/></div>")
.after("body p:first-child")
.show('slide')
.find("#y, #n").click(function() { $("form #hasAsked").val("true") /* default: false */; })
.end()
.find("#y")
.click(function() { $("form #hiddenbuy").val("true"); })
.end()
.find("#n")
.click(function() { $("form #hiddenbuy").val("false"); })
}
Related
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>
I'm using some jQuery to do some form validation. The following is the validation script.
$(document).ready(function() {
$('#contact-form').validate({
rules: {
cf_name: {
minlength: 2,
required: true
},
cf_email: {
required: true,
email: true
},
phone: {
minlength: 10,
required: true
},
user_pass: {
minlength: 2,
required: true
},
validateSelect: {
required: true
},
validateCheckbox: {
required: true,
minlength: 2
},
validateRadio: {
required: true
}
},
focusCleanup: false,
highlight: function(label) {
$(label).closest('.control-group').removeClass('success').addClass('error');
},
success: function(label) {
label
//.text('OK!').addClass('valid')
.closest('.control-group').addClass('success');
},
errorPlacement: function(error, element) {
error.appendTo(element.parents('.controls'));
}
});
$('.form').eq(0).find('input').eq(0).focus();
}); // end document.ready
On my submit button, I have this code:
<input type="submit" value="SUBMIT" id="sub" class="sub_text">
I'd like to make it so that when a user clicks the submit button and the form validates before it does any fading/transitioning, that it does within this code:
$("#sub").click(function(){
$("#forms").fadeOut( 1000 );
$("#overlay1").delay(1000).fadeIn( 1000 );
});
But my problem is that if a user forgets a field and then hits submit, the overlay transition happens. I'd like it to only happen when there's a
success of validation.
How am I able to trigger the event only when it's validated?
Have you tried calling form.valid() as follows:
$("#sub").click(function(){
if($('#contact-form').valid()){
$("#forms").fadeOut( 1000 );
$("#overlay1").delay(1000).fadeIn( 1000 );
}
});
.valid() checks whether given form is valid or not.
You are using the wrong hook. You are attaching your fadein code into "click" event of the button, means just when the user clicks the button you will execute the fadein.
Solution? quite simple, just have a look at the jqueryvalidation doc (http://jqueryvalidation.org/validate), instead of fadein in click event of the button, just do it in the validation hook.
$('#contact-form').validate({
submitHandler: function(form) {
$("#forms").fadeOut( 1000 );
$("#overlay1").delay(1000).fadeIn( 1000 );
// do other things for a valid form
form.submit();
}
});
I'm new to jQuery.
Working with jQuery validation plugin & cufon at the same time is giving me really hard time.
Basically, I want to detect event once jQuery Validation did what it had to do and call Cufon.refresh() straight after it.
$('#commentForm').validate({
rules: {
password: {
required: true,
minlength: 8,
maxlength: 8,
number: true
},
}
});
We are expecting <label class="error"> SOME TEXT </label> when form is not valid.
And once that created I want to Cufon.refresh() on that label created by jQuery Validation.
How can I detect when jQuery Validation is done, and call something based on that event?
Any help much appreciated.
Regards,
Piotr
Thanks to #Ariel - if there is a 'success' there has to be a 'not-success' as well, so..
Working code:
$('#commentForm').validate({
rules: {
password: {
required: true,
minlength: 8,
maxlength: 8,
number: true
}
},
showErrors: function(errorMap, errorList) {
this.defaultShowErrors();
Cufon.refresh();
//alert('not valid!')
},
success: function() {
//alert('valid!')
}
});
Thanks again for the idea!
Use the success option:
$('#commentForm').validate({
rules: {
password: {
required: true,
minlength: 8,
maxlength: 8,
number: true
},
}
success: function() { .... }
});
Note that you have an extra comma after the close brace for the password object. This will give an error in IE.
<script src="js/validate/jquery-1.11.1.min.js"></script>
<script src="js/validate/jquery.validate.min.js"></script>
<script src="js/validate/additional-methods.min.js"></script>
<script>
jQuery.validator.setDefaults({
success: "valid"
});
var form = $("#myform");
form.validate({
rules: {
name: {required: true, minlength: 2},
lastname: {required: true, minlength: 2}
}
});
$("#button").click(function() {
if(form.valid() == true ) { // here you check if validation returned true or false
$("body").addClass("loading");
}
})
</script>
submitHandler: { function(){ bla bla }}
This will allow you to execute code upon the completion of the validate. you will need to place a submit form snippet though, since it replaces the default handler.
EDIT:
// specifying a submitHandler prevents the default submit
submitHandler: function() {
alert("submitted!");
},
// set this class to error-labels to indicate valid fields
success: function(label) {
// set as text for IE
label.html(" ").addClass("checked");
}
You can use either to do what you want. submitHandler allows you to stop the submit and execute code instead ( you can possibly use it to perform code BEFORE you submit it ) or success to execute code after the submit.
Put it inside the errorPlacement option.
errorPlacement: function(error, element) {
error.appendTo( element.parent() );
yourCodeHere();
}
$(document).ready(function() {
$('#commentForm').submit(function(){
var validationResponse = $('#commentForm').valid();
if(validationResponse) {
// when true, your logic
} else {
// when false, your logic
return false;
}
});
$("#commentForm" ).validate({
rules: {
"first_name": {
required: true
}
},
messages: {
"first_name": {
required: "First Name can not be empty"
}
}
});
});
I use Jquery form validation to validate form input data. There is a
confirm
check on
submit
of this form.
.
The code is:
<script type="text/javascript">
function Confirmation(){
var answer = confirm("Do you really want to withdraw this amount of money from your account?")
if (answer){
return true;
}
else{
return false;
}
}
$(document).ready(function() {
$("#withdraw").validate({
rules: {
amount: {
required: true,
digits:true
} ,
bank:{
required:true,
},
cardnumber1: {
required: true,
minlength:8
},
cardnumber2:{
required:true,
equalTo: "#cardnumber1"
},
holder:{
required:true,
}
}
})
});
</script>
I want the Jquery form validation is executed before the Confirmation(), how to do it?
Steven,
You need to remove the onsubmit handler from the form and add it the the submitHandler of the validate plugin ...
$("#withdraw").validate({
rules: {
amount: {
required: true,
digits:true
}
// .. other rules here
},
submitHandler: function(form){
if( Confirmation() )
form.submit();
}
})
I looked at the documentation and there is an option named submitHandler which I think would allow you to add your confirmation dialog before the form is submitted but after the validation happens. Try this...
<script type="text/javascript">
$(document).ready(function() {
$("#withdraw").validate({
submitHandler : function(form) {
if (confirm("Do you really want to withdraw this amount of money from your account?")) {
form.submit();
}
},
rules: {
amount: {
required: true,
digits:true
},
bank:{
required:true,
},
cardnumber1: {
required: true,
minlength:8
},
cardnumber2:{
required:true,
equalTo: "#cardnumber1"
},
holder:{
required:true,
}
}
})
});
</script>
I am trying to make the Validation plugin work. It works fine for individual fields, but when I try to include the demo code for the error container that contains all of the errors, I have an issue. The problem is that it shows the container with all errors when I am in all fields, but I would like to display the error container only when the user presses the submit button (but still show inline errors beside the control when losing focus).
The problem is the message in the container. When I took off the code as mentioned in the answer below for the container, the container output just displays the number of errors in plain text.
What is the trick to get a list of detailed error messages? What I would like is to display "ERROR" next to the control in error when the user presses the tab button, and to have a summary of everything at the end when he presses submit. Is that possible?
Code with all input from here:
$().ready(function() {
var container = $('div.containererreurtotal');
// validate signup form on keyup and submit
$("#frmEnregistrer").bind("invalid-form.validate", function(e, validator) {
var err = validator.numberOfInvalids();
if (err) {
container.html("THERE ARE "+ err + " ERRORS IN THE FORM")
container.show();
} else {
container.hide();
}
}).validate({
rules: {
nickname_in: {
required: true,
minLength: 4
},
prenom_in: {
required: true,
minLength: 4
},
nom_in: {
required: true,
minLength: 4
},
password_in: {
required: true,
minLength: 4
},
courriel_in: {
required: true,
email: true
},
userdigit: {
required: true
}
},
messages: {
nickname_in: "ERROR",
prenom_in: "ERROR",
nom_in: "ERROR",
password_in: "ERROR",
courriel_in: "ERROR",
userdigit: "ERROR"
}
,errorPlacement: function(error, element){
container.append(error.clone());
error.insertAfter(element);
}
});
});
First your container should be using an ID instead of a class.. (I'm going to assume that ID is 'containererreurtotal')
Then Try this..
$().ready(function() {
$('div#containererreurtotal').hide();
// validate signup form on keyup and submit
$("#frmEnregistrer").validate({
errorLabelContainer: "#containererreurtotal",
wrapper: "p",
errorClass: "error",
rules: {
nickname_in: { required: true, minLength: 4 },
prenom_in: { required: true, minLength: 4 },
nom_in: { required: true, minLength: 4 },
password_in: { required: true, minLength: 4 },
courriel_in: { required: true, email: true },
userdigit: { required: true }
},
messages: {
nickname_in: { required: "Nickname required!", minLength: "Nickname too short!" },
prenom_in: { required: "Prenom required!", minLength: "Prenom too short!" },
nom_in: { required: "Nom required!", minLength: "Nom too short!" },
password_in: { required: "Password required!", minLength: "Password too short!" },
courriel_in: { required: "Courriel required!", email: "Courriel must be an Email" },
userdigit: { required: "UserDigit required!" }
},
invalidHandler: function(form, validator) {
$("#containererreurtotal").show();
},
unhighlight: function(element, errorClass) {
if (this.numberOfInvalids() == 0) {
$("#containererreurtotal").hide();
}
$(element).removeClass(errorClass);
}
});
});
I am assuming here that you want a <p> tag around each of the individual errors. Typically I use a <ul> container for the actual container (instead of the div you used called 'containererreurtotal') and a <li> for each error (this element is specified in the "wrapper" line)
If you specify #containererreurtotal as display: none; in your CSS, then you dont need the first line in the ready function ( $('div#containererreurtotal').hide(); )
You will find the documentation for the meta option in http://docs.jquery.com/Plugins/Validation/validate#toptions
If you want to display the errors beside the inputs AND in a separate error container you will need to override the errorPlacement callback.
From your example:
...
courriel_in: "ERROR",
userdigit: "ERROR"
}
,errorContainer: container
,errorPlacement: function(error, element){
var errorClone = error.clone();
container.append(errorClone);
error.insertAfter(element)
}
// We don't need this options
//,errorLabelContainer: $("ol", container)
//,wrapper: 'li'
//,meta: "validate"
});
...
The error parameter is a jQuery object containing a <label> tag. The element parameter is the input that has failed validation.
Update to comments
With the above code the error container will not clear errors because it contains a cloned copy. It's easy to solve this if jQuery gives a "hide" event, but it doesn't exist. Let's add a hide event!
First we need the AOP plugin
We add an advice for the hide method:
jQuery.aop.before({target: jQuery.fn, method: "hide"},
function(){
this.trigger("hide");
});
We bind the hide event to hide the cloned error:
...
,errorPlacement: function(error, element){
var errorClone = error.clone();
container.append(errorClone);
error.insertAfter(element).bind("hide", function(){
errorClone.hide();
});
}
...
Give it a try
I would remove the errorContainer and then intercept the validation on postback and in there add a container-error manually like this:
$("#frmEnregistrer").bind("invalid-form.validate", function(e, validator) {
var err = validator.numberOfInvalids();
if (err) {
container.html("THERE ARE "+ err + " ERRORS IN THE FORM")
container.show();
} else {
container.hide();
}
}).validate({ ... })
I have a slightly different solution:
jQuery(document).ready(function() {
var submitted = false;
var validator = jQuery("#emailForm").validate({
showErrors: function(errorMap, errorList) {
if (submitted) {
var summary = "";
jQuery.each(errorList, function() {
summary += "<li><label for='"+ this.element.name;
summery += "' class='formError'>" + this.message + "</label></li>"; });
jQuery("#errorMessageHeader").show();
jQuery("#errorMessageHeader").children().after().html(summary);
submitted = false;
}
this.defaultShowErrors();
},
invalidHandler: function(form, validator) { submitted = true; },
onfocusout: function(element) { this.element(element); },
errorClass: "formError",
rules: {
//some validation rules
},
messages: {
//error messages to be displayed
}
});
});
I solved this problem with the following short code:
errorElement: "td",
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
My structure is the following:
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name"></td>
</tr>
</table>
So my errors will now shown directly in a <td> behind my <input>
I don't know if the validation plugin provides an option for this, but you can probably use standard jQuery to achieve what you want. Make sure you're container is initially hidden, by setting the display style to none:
<div id="container" style="display:none;"></div>
Then you can hookup an onsubmit event to the form which will make the container visible as soon as an attempt is made to submit the form:
jQuery('#formId').onsubmit(function() {
// This will be called before the form is submitted
jQuery('#container').show();
});
Hopefully combining that with your existing code should do the trick.