I was wondering how to display a single error message above the form instead of individual field messages. like this form has http://jquery.bassistance.de/validate/demo/marketo/step2.htm
I know it has something to do with handles but not exactly sure how or where to put them
<script>
$(document).ready(function(){
$("#valform").validate();
});
</script>
this is the code i have that uses all default validation
You should use invalidHandler for this functionality. Something like this should do:
$("#myform").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$("#error-message").show().text("You missed " + errors + " field(s)");
} else {
$("#error-message").hide();
}
}
});
Example: http://jsfiddle.net/KheRr/1/
If you want to hide the default error messages, you should specify "" as the error message for the field and validation type:
$("#myform").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
$("#error-message").show().text("You missed " + errors + " field(s)");
} else {
$("#error-message").hide();
}
},
messages: {
field1: {
required: "" // You'll have to do this for each field and validation type.
}
}
});
Example: http://jsfiddle.net/KheRr/2/
Related
I'm stuck at this point now. I never used braintree API before. The problem is when I hit the submit button it is showing alert box with my payment_method_nonce.
It means I'm successfully getting the payment_method_nonce from the client, But the problem is I don't know how can I submit a the form with this payment_method_nonce.
This client sdk is written in jquery.
And I tried several ways to submit the form but I don't know exactly how can I get a 'payment_method_nonce' when submitting a form.
I tired adding a hidden type field. And even that hidden type field doesn't comes up.
Please help. Here is the jquery code.
I just want to know how can I submit a form in jquery with that 'payment_method_nonce'.
braintree.client.create({
authorization: '{{$clientToken}}'
}, function (err, clientInstance) {
if (err) {
console.error(err);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px',
'font-family': 'helvetica, tahoma, calibri, sans-serif',
'color': '#3a3a3a'
},
':focus': {
'color': 'black'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationMonth: {
selector: '#expiration-month',
placeholder: 'MM'
},
expirationYear: {
selector: '#expiration-year',
placeholder: 'YY'
},
postalCode: {
selector: '#postal-code',
placeholder: '90210'
}
}
}, function (err, hostedFieldsInstance) {
if (err) {
console.error(err);
return;
}
hostedFieldsInstance.on('validityChange', function (event) {
var field = event.fields[event.emittedBy];
if (field.isValid) {
if (event.emittedBy === 'expirationMonth' || event.emittedBy === 'expirationYear') {
if (!event.fields.expirationMonth.isValid || !event.fields.expirationYear.isValid) {
return;
}
} else if (event.emittedBy === 'number') {
$('#card-number').next('span').text('');
}
// Remove any previously applied error or warning classes
$(field.container).parents('.form-group').removeClass('has-warning');
$(field.container).parents('.form-group').removeClass('has-success');
// Apply styling for a valid field
$(field.container).parents('.form-group').addClass('has-success');
} else if (field.isPotentiallyValid) {
// Remove styling from potentially valid fields
$(field.container).parents('.form-group').removeClass('has-warning');
$(field.container).parents('.form-group').removeClass('has-success');
if (event.emittedBy === 'number') {
$('#card-number').next('span').text('');
}
} else {
// Add styling to invalid fields
$(field.container).parents('.form-group').addClass('has-warning');
// Add helper text for an invalid card number
if (event.emittedBy === 'number') {
$('#card-number').next('span').text('Looks like this card number has an error.');
}
}
});
hostedFieldsInstance.on('cardTypeChange', function (event) {
// Handle a field's change, such as a change in validity or credit card type
if (event.cards.length === 1) {
$('#card-type').text(event.cards[0].niceType);
} else {
$('#card-type').text('Card');
}
});
$('.panel-body').submit(function (event) {
//event.preventDefault();
hostedFieldsInstance.tokenize(function (err, payload) {
if (err) {
console.error(err);
return;
}
// This is where you would submit payload.nonce to your server
alert('Submit your nonce to your server here!' + payload.nonce);
});
});
});
});
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact
support.
Without your form, or HTML code included, it's tough to know if you've defined your form as a variable. Essentially, though, you'll want to inject that nonce value (payload.nonce) into your form, following which you'll submit that form to your server.
For example, I have defined my form (above my braintree.client.create)
var form = document.querySelector('#checkout-form');
Then, in your submit event, you'll want to inject the payload value into your form after a successful tokenization (which you've seemed to achieve based on the alert value)
document.querySelector('input[name="payment_method_nonce"]').value = payload.nonce;
Subsequently submitting your form;
form.submit()
This will submit your form with an input named payment_method_nonce, which you can then request on your server.
Let me know if I can further clarify. Happy to help.
When I am uploading Image then validation working properly But When I am
updating Image I want to validate Input type file is empty or not. How to check
it?
Actually I want to use same validation function which is using for Upload image(create image) during Update?
How can I do that?validation function is like:->
var teacherValidation = function() {
// for more info visit the official plugin documentation:
// http://docs.jquery.com/Plugins/Validation
var form1 = $('#form_teacher');
var error1 = $('.alert-danger', form1);
var success1 = $('.alert-success', form1);
form1.validate({
errorElement: 'span', //default input error message container
errorClass: 'help-block help-block-error', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "", // validate all fields including form hidden input
messages: {
select_multi: {
maxlength: jQuery.validator.format("Max {0} items allowed for selection"),
minlength: jQuery.validator.format("At least {0} items must be selected")
}
},
rules: {
fileData: {
required: true
}
},
submitHandler: function (form) {
success1.show();
error1.hide();
form.submit();
}
});
}
In your case you can use your own custom function to validate the file is required in first upload and update time
$(document).ready(function(){
jQuery.validator.addMethod("filetype", function(value, element) {
var types = ['jpeg', 'jpg', 'png'],
ext = value.replace(/.*[.]/, '').toLowerCase();
if (types.indexOf(ext) !== -1) {
return true;
}
return false;
},"Please select allowed file");
$('#frm').validate({
rules:
{
file:
{
filetype: true
}
}
});
});
I am currently using Django 1.9 and Braintree payments JS v3. What I want to be able to do is when the user submits the form successfully, have a Javascript alert() pop up. But the pop-up message will be contingent on what the back end Python returns...
So like this:
Submit the form
Run the backend stuff
Pop up the alert with a message dependent on what is returned by the Python backend
When the alert is closed, refresh or redirect
var client_token = "{{ request.session.braintree_client_token }}"
var form = document.querySelector('#checkout-form');
var submit = document.querySelector('input[type="submit"]');
braintree.client.create({
authorization: client_token
}, function (clientErr, clientInstance) {
if (clientErr) { // for error loading client authorization
if(alert('There was a form verification issue, reloading page on close.')){}
else window.location.reload();
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '14px'
},
'input.invalid': {
'color': 'red'
},
'input.valid': {
'color': 'green'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: 'Credit Card Number'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10/2019'
},
postalCode: {
selector: '#postal-code',
placeholder: '10014'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) { // for errors creating form
if(alert('There was a form creation issue, reloading page on close.')){}
else window.location.reload();
return;
}
submit.removeAttribute('disabled');
form.addEventListener('submit', function (event) {
event.preventDefault();
document.querySelector('input[id="pay-button"]').value = "Please wait...";
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
if (tokenizeErr.code === 'HOSTED_FIELDS_FIELDS_EMPTY') {
alert('Please fill in card info');
document.querySelector('input[id="pay-button"]').value = "Complete Booking";
}
return;
}
// Put `payload.nonce` into the `payment_method_nonce`
document.querySelector('input[name="payment_method_nonce"]').value = payload.nonce;
form.submit();
$('input[type="submit"]').prop('disabled',true);
});
}, false);
});
});
I'm thinking that this functionality would need to be right after form.submit() is run on the bottom...
Edit:
I added the vars up top in my code
Is it possible to add an error message for an element in a custom validation function?
HTML:
<form action="#">
<div id="appDiv">
<input name="nEle" type="hidden" value="validate" />
</div>
<br/>
<input name="nEle1" />
<br/>
<input name="nEle2" />
<br/>
<input name="nEle3" />
<br/>
<input name="nEle4" />
<br/>
<br/>
<input type="submit" />
</form>
JQuery:
(function (window, $) {
function Plugin(ele, params) {
return this;
};
Plugin.prototype = {
isValid: function () {
/* After some validation, suppose this raises error and returns false */
return false;
},
getErrors: function () {
/* The validation logic in "isValid" stores the error in the plugin context and this function gets the errors form it and returns */
return "Error evaluated in plugin after its own validation.";
}
}
$.fn.plugin = function (params) {
var retval = this,
initlist = this;
initlist.each(function () {
var p = $(this).data("plugindata");
if (!p) {
$(this).data('plugindata', new Plugin(this, params));
} else {
if (typeof params === 'string' && typeof p[params] === 'function') {
retval = p[params]();
initlist = false;
}
}
});
return retval || initlist;
};
})(window, jQuery);
$.validator.addMethod("customValidation", function (value, element, jqPlugin) {
if (!jqPlugin.plugin('isValid')) {
var errorString = jqPlugin.plugin('getErrors');
console.log("Error String : %s", errorString);
alert("How to set this as error : " + errorString);
/* How to display the error informaiton which is in the errorString ? */
return false;
}
return true;
}, "Default custom validation message.");
$(document).ready(function () {
var jqPlugin = $('#appDiv').plugin();
$('form').validate({
ignore: [],
onkeyup: false,
onclick: false,
onfocusout: false,
rules: {
nEle: {
required: true,
customValidation: jqPlugin
},
nEle1: {
required: true,
},
nEle2: {
required: true,
},
nEle3: {
required: true,
},
nEle4: {
required: true,
},
},
messages: {
nEle: {
customValidation: "Fix error with custom validation."
}
},
submitHandler: function (form) {
alert("Validaton Success..!!");
return false;
}
});
});
JQuery - A probable fix, only deltas :
$.validator.addMethod("customValidation", function (value, element, jqPlugin) {
if (!jqPlugin.plugin('isValid')) {
var errorString = jqPlugin.plugin('getErrors');
console.log("Error String : %s", errorString);
alert("How to set this as error : " + errorString);
/* How to display the error informaiton which is in the errorString ? */
this.errorList.push({
message: errorString,
element: element
});
this.errorMap[$(element).attr('name')] = status.error;
// return false;
}
return true;
}, "Default custom validation message.");
CSS :
div {
width: 150px;
height: 150px;
border: 1px solid black;
margin-bottom: 10px;
}
jsfiddle:
http://jsfiddle.net/m8eEs - Original Code
http://jsfiddle.net/m8eEs/1/ - Updated for clarity
http://jsfiddle.net/m8eEs/2/ - A probable fix which I'm still not happy with, not sure if this is the only way to do it..!!
In the above, I would like to add error message in the function "customValidation" for the element "nEle".
Edited: Maybe its better to add the reason for this kind of question. (directly copied from the comments below)
I know that. But I need to add the error message inside the function. The reason is, element creation & validation(application specific validation, not only the supported required/number/range..) logic is done in a separate plugin(say 'X'). And a set of APIs is exposed to get the validation status and the errors if any. But this element is grouped along with other elements that are validated through the 'validation' plugin. So, in a nutshell, the "customValidation" function just calls the APIs from the 'X' plugin and get the validation status & error messages if any, but stuck with showing it.
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.