Created
June 7, 2013 03:18
-
-
Save jonathanconway/5726858 to your computer and use it in GitHub Desktop.
When called, shows a validation message using jQuery Validation. Can also optionally display the message in the validation summary.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
$.showError = function(element, errorMessage, showInSummary, summaryLinkTargetElement) { | |
var $element = $(element); | |
var $form = $element.parents('form').first(); | |
var elementName = $element.attr('name'); | |
var elementLabel = $('label[for={0}]>span:first'.format(elementName)).text(); | |
var $validationSummary; | |
var $validationLink; | |
var $target = !summaryLinkTargetElement ? $element : $(summaryLinkTargetElement); | |
var errors = {}; | |
errors[elementName] = errorMessage; | |
$form.validate().showErrors(errors); | |
if (showInSummary) { | |
$form.find('.validation-summary-valid').removeClass('validation-summary-valid').addClass('validation-summary-errors'); | |
$validationSummary = $form.find('.validation-summary-errors'); | |
$validationSummary.find('ul').prepend( | |
('<li data-valmsg-for="{0}" style="">' + | |
' <a role="button" href="#{0}" tabindex="0">{1}</a>' + | |
'</li>').format(elementName, elementLabel)); | |
$validationLink = $('.validation-summary-errors a[href="#{0}"]'.format(elementName)); | |
$(window).scrollTop($validationSummary.offset().top); | |
$validationLink.click(function(e) { | |
e.preventDefault(); | |
$target.focus(); | |
}); | |
} | |
}; | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @jonathan
Can you explain this ??