lavkach3
1198 строк · 45.6 Кб
1/* jqBootstrapValidation
2* A plugin for automating validation on Twitter Bootstrap formatted forms.
3*
4* v1.3.6
5*
6* License: MIT <http://opensource.org/licenses/mit-license.php> - see LICENSE file
7*
8* http://ReactiveRaven.github.com/jqBootstrapValidation/
9*/
10(function ($) {11var createdElements = [];12var defaults = {13options: {14prependExistingHelpBlock: false,15sniffHtml: true, // sniff for 'required', 'maxlength', etc16preventSubmit: true, // stop the form submit event from firing if validation fails17submitError: false, // function called if there is an error when trying to submit18submitSuccess: false, // function called just before a successful submit event is sent to the server19semanticallyStrict: false, // set to true to tidy up generated HTML output20bindEvents: [],21autoAdd: {22helpBlocks: true,23},24filter: function () {25// return $(this).is(":visible"); // only validate elements you can see26return true; // validate everything27},28},29methods: {30init: function (options) {31var settings = $.extend(true, {}, defaults);32settings.options = $.extend(true, settings.options, options);33var $siblingElements = this;34var uniqueForms = $.unique(35$siblingElements
36.map(function () {37return $(this).parents("form")[0];38})39.toArray()40);41$(uniqueForms).bind("submit.validationSubmit", function (e) {42var $form = $(this);43var warningsFound = 0;44var $allInputs = $form45.find("input,textarea,select")46.not("[type=submit],[type=image]")47.filter(settings.options.filter);48var $allControlGroups = $form.find(".form-group");49var $inputsWithValidators = $allInputs.filter(function () {50return $(this).triggerHandler("getValidatorCount.validation") > 0;51});52$inputsWithValidators.trigger("submit.validation");53$allInputs.trigger("validationLostFocus.validation");54$allControlGroups.each(function (i, el) {55var $controlGroup = $(el);56if (57$controlGroup.hasClass("issue") ||58$controlGroup.hasClass("error")59) {60$controlGroup.removeClass("issue").addClass("error");61warningsFound++;62}63});64if (warningsFound) {65if (settings.options.preventSubmit) {66e.preventDefault();67e.stopImmediatePropagation();68}69$form.addClass("error");70if ($.isFunction(settings.options.submitError)) {71settings.options.submitError(72$form,73e,74$inputsWithValidators.jqBootstrapValidation(75"collectErrors",76true77)78);79}80} else {81$form.removeClass("error");82if ($.isFunction(settings.options.submitSuccess)) {83settings.options.submitSuccess($form, e);84}85}86});87return this.each(function () {88var $this = $(this),89$controlGroup = $this.parents(".form-group").first(),90$helpBlock = $controlGroup.find(".help-block").first(),91$form = $this.parents("form").first(),92validatorNames = [];93if (94!$helpBlock.length &&95settings.options.autoAdd &&96settings.options.autoAdd.helpBlocks97) {98$helpBlock = $('<div class="help-block" />');99$controlGroup.find(".controls").append($helpBlock);100createdElements.push($helpBlock[0]);101}102if (settings.options.sniffHtml) {103var message;104if ($this.data("validationPatternPattern")) {105$this.attr("pattern", $this.data("validationPatternPattern"));106}107if ($this.attr("pattern") !== undefined) {108message =109"Not in the expected format<!-- data-validation-pattern-message to override -->";110if ($this.data("validationPatternMessage")) {111message = $this.data("validationPatternMessage");112}113$this.data("validationPatternMessage", message);114$this.data("validationPatternRegex", $this.attr("pattern"));115}116if (117$this.attr("max") !== undefined ||118$this.attr("aria-valuemax") !== undefined119) {120var max =121$this.attr("max") !== undefined122? $this.attr("max")123: $this.attr("aria-valuemax");124message =125"Too high: Maximum of '" +126max +127"'<!-- data-validation-max-message to override -->";128if ($this.data("validationMaxMessage")) {129message = $this.data("validationMaxMessage");130}131$this.data("validationMaxMessage", message);132$this.data("validationMaxMax", max);133}134if (135$this.attr("min") !== undefined ||136$this.attr("aria-valuemin") !== undefined137) {138var min =139$this.attr("min") !== undefined140? $this.attr("min")141: $this.attr("aria-valuemin");142message =143"Too low: Minimum of '" +144min +145"'<!-- data-validation-min-message to override -->";146if ($this.data("validationMinMessage")) {147message = $this.data("validationMinMessage");148}149$this.data("validationMinMessage", message);150$this.data("validationMinMin", min);151}152if ($this.attr("maxlength") !== undefined) {153message =154"Too long: Maximum of '" +155$this.attr("maxlength") +156"' characters<!-- data-validation-maxlength-message to override -->";157if ($this.data("validationMaxlengthMessage")) {158message = $this.data("validationMaxlengthMessage");159}160$this.data("validationMaxlengthMessage", message);161$this.data(162"validationMaxlengthMaxlength",163$this.attr("maxlength")164);165}166if ($this.attr("minlength") !== undefined) {167message =168"Too short: Minimum of '" +169$this.attr("minlength") +170"' characters<!-- data-validation-minlength-message to override -->";171if ($this.data("validationMinlengthMessage")) {172message = $this.data("validationMinlengthMessage");173}174$this.data("validationMinlengthMessage", message);175$this.data(176"validationMinlengthMinlength",177$this.attr("minlength")178);179}180if (181$this.attr("required") !== undefined ||182$this.attr("aria-required") !== undefined183) {184message = settings.builtInValidators.required.message;185if ($this.data("validationRequiredMessage")) {186message = $this.data("validationRequiredMessage");187}188$this.data("validationRequiredMessage", message);189}190if (191$this.attr("type") !== undefined &&192$this.attr("type").toLowerCase() === "number"193) {194message = settings.validatorTypes.number.message;195if ($this.data("validationNumberMessage")) {196message = $this.data("validationNumberMessage");197}198$this.data("validationNumberMessage", message);199var step = settings.validatorTypes.number.step;200if ($this.data("validationNumberStep")) {201step = $this.data("validationNumberStep");202}203$this.data("validationNumberStep", step);204var decimal = settings.validatorTypes.number.decimal;205if ($this.data("validationNumberDecimal")) {206decimal = $this.data("validationNumberDecimal");207}208$this.data("validationNumberDecimal", decimal);209}210if (211$this.attr("type") !== undefined &&212$this.attr("type").toLowerCase() === "email"213) {214message =215"Not a valid email address<!-- data-validation-email-message to override -->";216if ($this.data("validationEmailMessage")) {217message = $this.data("validationEmailMessage");218}219$this.data("validationEmailMessage", message);220}221if ($this.attr("minchecked") !== undefined) {222message =223"Not enough options checked; Minimum of '" +224$this.attr("minchecked") +225"' required<!-- data-validation-minchecked-message to override -->";226if ($this.data("validationMincheckedMessage")) {227message = $this.data("validationMincheckedMessage");228}229$this.data("validationMincheckedMessage", message);230$this.data(231"validationMincheckedMinchecked",232$this.attr("minchecked")233);234}235if ($this.attr("maxchecked") !== undefined) {236message =237"Too many options checked; Maximum of '" +238$this.attr("maxchecked") +239"' required<!-- data-validation-maxchecked-message to override -->";240if ($this.data("validationMaxcheckedMessage")) {241message = $this.data("validationMaxcheckedMessage");242}243$this.data("validationMaxcheckedMessage", message);244$this.data(245"validationMaxcheckedMaxchecked",246$this.attr("maxchecked")247);248}249}250if ($this.data("validation") !== undefined) {251validatorNames = $this.data("validation").split(",");252}253$.each($this.data(), function (i, el) {254var parts = i.replace(/([A-Z])/g, ",$1").split(",");255if (parts[0] === "validation" && parts[1]) {256validatorNames.push(parts[1]);257}258});259var validatorNamesToInspect = validatorNames;260var newValidatorNamesToInspect = [];261var uppercaseEachValidatorName = function (i, el) {262validatorNames[i] = formatValidatorName(el);263};264var inspectValidators = function (i, el) {265if ($this.data("validation" + el + "Shortcut") !== undefined) {266$.each(267$this.data("validation" + el + "Shortcut").split(","),268function (i2, el2) {269newValidatorNamesToInspect.push(el2);270}271);272} else if (settings.builtInValidators[el.toLowerCase()]) {273var validator = settings.builtInValidators[el.toLowerCase()];274if (validator.type.toLowerCase() === "shortcut") {275$.each(validator.shortcut.split(","), function (i, el) {276el = formatValidatorName(el);277newValidatorNamesToInspect.push(el);278validatorNames.push(el);279});280}281}282};283do {284$.each(validatorNames, uppercaseEachValidatorName);285validatorNames = $.unique(validatorNames);286newValidatorNamesToInspect = [];287$.each(validatorNamesToInspect, inspectValidators);288validatorNamesToInspect = newValidatorNamesToInspect;289} while (validatorNamesToInspect.length > 0);290var validators = {};291$.each(validatorNames, function (i, el) {292var message = $this.data("validation" + el + "Message");293var hasOverrideMessage = !!message;294var foundValidator = false;295if (!message) {296message =297"'" +298el +299"' validation failed <!-- Add attribute 'data-validation-" +300el.toLowerCase() +301"-message' to input to change this message -->";302}303$.each(304settings.validatorTypes,305function (validatorType, validatorTemplate) {306if (validators[validatorType] === undefined) {307validators[validatorType] = [];308}309if (310!foundValidator &&311$this.data(312"validation" +313el +314formatValidatorName(validatorTemplate.name)315) !== undefined316) {317var initted = validatorTemplate.init($this, el);318if (hasOverrideMessage) {319initted.message = message;320}321validators[validatorType].push(322$.extend(323true,324{325name: formatValidatorName(validatorTemplate.name),326message: message,327},328initted
329)330);331foundValidator = true;332}333}334);335if (336!foundValidator &&337settings.builtInValidators[el.toLowerCase()]338) {339var validator = $.extend(340true,341{},342settings.builtInValidators[el.toLowerCase()]343);344if (hasOverrideMessage) {345validator.message = message;346}347var validatorType = validator.type.toLowerCase();348if (validatorType === "shortcut") {349foundValidator = true;350} else {351$.each(352settings.validatorTypes,353function (validatorTemplateType, validatorTemplate) {354if (validators[validatorTemplateType] === undefined) {355validators[validatorTemplateType] = [];356}357if (358!foundValidator &&359validatorType === validatorTemplateType.toLowerCase()360) {361$this.data(362"validation" +363el +364formatValidatorName(validatorTemplate.name),365validator[validatorTemplate.name.toLowerCase()]366);367validators[validatorType].push(368$.extend(validator, validatorTemplate.init($this, el))369);370foundValidator = true;371}372}373);374}375}376if (!foundValidator) {377$.error("Cannot find validation info for '" + el + "'");378}379});380$helpBlock.data(381"original-contents",382$helpBlock.data("original-contents")383? $helpBlock.data("original-contents")384: $helpBlock.html()385);386$helpBlock.data(387"original-role",388$helpBlock.data("original-role")389? $helpBlock.data("original-role")390: $helpBlock.attr("role")391);392$controlGroup.data(393"original-classes",394$controlGroup.data("original-clases")395? $controlGroup.data("original-classes")396: $controlGroup.attr("class")397);398$this.data(399"original-aria-invalid",400$this.data("original-aria-invalid")401? $this.data("original-aria-invalid")402: $this.attr("aria-invalid")403);404$this.bind("validation.validation", function (event, params) {405var value = getValue($this);406var errorsFound = [];407$.each(validators, function (validatorType, validatorTypeArray) {408if (409value ||410value.length ||411(params && params.includeEmpty) ||412!!settings.validatorTypes[validatorType].includeEmpty ||413(!!settings.validatorTypes[validatorType].blockSubmit &&414params &&415!!params.submitting)416) {417$.each(validatorTypeArray, function (i, validator) {418if (419settings.validatorTypes[validatorType].validate(420$this,421value,422validator
423)424) {425errorsFound.push(validator.message);426}427});428}429});430return errorsFound;431});432$this.bind("getValidators.validation", function () {433return validators;434});435var numValidators = 0;436$.each(validators, function (i, el) {437numValidators += el.length;438});439$this.bind("getValidatorCount.validation", function () {440return numValidators;441});442$this.bind("submit.validation", function () {443return $this.triggerHandler("change.validation", {444submitting: true,445});446});447$this.bind(448(settings.options.bindEvents.length > 0449? settings.options.bindEvents450: [451"keyup",452"focus",453"blur",454"click",455"keydown",456"keypress",457"change",458]459)460.concat(["revalidate"])461.join(".validation ") + ".validation",462function (e, params) {463var value = getValue($this);464var errorsFound = [];465if (params && !!params.submitting) {466$controlGroup.data("jqbvIsSubmitting", true);467} else if (e.type !== "revalidate") {468$controlGroup.data("jqbvIsSubmitting", false);469}470var formIsSubmitting = !!$controlGroup.data("jqbvIsSubmitting");471$controlGroup
472.find("input,textarea,select")473.not("[type=submit]")474.each(function (i, el) {475var oldCount = errorsFound.length;476$.each(477$(el).triggerHandler("validation.validation", params) || [],478function (j, message) {479errorsFound.push(message);480}481);482if (errorsFound.length > oldCount) {483$(el).attr("aria-invalid", "true");484} else {485var original = $this.data("original-aria-invalid");486$(el).attr(487"aria-invalid",488original !== undefined ? original : false489);490}491});492$form
493.find("input,select,textarea")494.not($this)495.not('[name="' + $this.attr("name") + '"]')496.trigger("validationLostFocus.validation");497errorsFound = $.unique(errorsFound.sort());498if (errorsFound.length) {499$controlGroup
500.removeClass("validate error issue")501.addClass(formIsSubmitting ? "error" : "issue");502if (503settings.options.semanticallyStrict &&504errorsFound.length === 1505) {506$helpBlock.html(507errorsFound[0] +508(settings.options.prependExistingHelpBlock509? $helpBlock.data("original-contents")510: "")511);512} else {513$helpBlock.html(514'<ul role="alert"><li>' +515errorsFound.join("</li><li>") +516"</li></ul>" +517(settings.options.prependExistingHelpBlock518? $helpBlock.data("original-contents")519: "")520);521}522} else {523$controlGroup.removeClass("issue error validate");524if (value.length > 0) {525$controlGroup.addClass("validate");526}527$helpBlock.html($helpBlock.data("original-contents"));528}529if (e.type === "blur") {530if (settings.options.removeSuccess) {531}532}533}534);535$this.bind("validationLostFocus.validation", function () {536if (settings.options.removeSuccess) {537}538});539});540},541destroy: function () {542return this.each(function () {543var $this = $(this),544$controlGroup = $this.parents(".form-group").first(),545$helpBlock = $controlGroup.find(".help-block").first(),546$form = $this.parents("form").first();547$this.unbind(".validation");548$form.unbind(".validationSubmit");549$helpBlock.html($helpBlock.data("original-contents"));550$controlGroup.attr("class", $controlGroup.data("original-classes"));551$this.attr("aria-invalid", $this.data("original-aria-invalid"));552$helpBlock.attr("role", $this.data("original-role"));553if ($.inArray($helpBlock[0], createdElements) > -1) {554$helpBlock.remove();555}556});557},558collectErrors: function (includeEmpty) {559var errorMessages = {};560this.each(function (i, el) {561var $el = $(el);562var name = $el.attr("name");563var errors = $el.triggerHandler("validation.validation", {564includeEmpty: true,565});566errorMessages[name] = $.extend(true, errors, errorMessages[name]);567});568$.each(errorMessages, function (i, el) {569if (el.length === 0) {570delete errorMessages[i];571}572});573return errorMessages;574},575hasErrors: function () {576var errorMessages = [];577this.find("input,select,textarea")578.add(this)579.each(function (i, el) {580errorMessages = errorMessages.concat(581$(el).triggerHandler("getValidators.validation")582? $(el).triggerHandler("validation.validation", {583submitting: true,584})585: []586);587});588return errorMessages.length > 0;589},590override: function (newDefaults) {591defaults = $.extend(true, defaults, newDefaults);592},593},594validatorTypes: {595callback: {596name: "callback",597init: function ($this, name) {598var result = {599validatorName: name,600callback: $this.data("validation" + name + "Callback"),601lastValue: $this.val(),602lastValid: true,603lastFinished: true,604};605var message = "Not valid";606if ($this.data("validation" + name + "Message")) {607message = $this.data("validation" + name + "Message");608}609result.message = message;610return result;611},612validate: function ($this, value, validator) {613if (validator.lastValue === value && validator.lastFinished) {614return !validator.lastValid;615}616if (validator.lastFinished === true) {617validator.lastValue = value;618validator.lastValid = true;619validator.lastFinished = false;620var rrjqbvValidator = validator;621var rrjqbvThis = $this;622executeFunctionByName(623validator.callback,624window,625$this,626value,627function (data) {628if (rrjqbvValidator.lastValue === data.value) {629rrjqbvValidator.lastValid = data.valid;630if (data.message) {631rrjqbvValidator.message = data.message;632}633rrjqbvValidator.lastFinished = true;634rrjqbvThis.data(635"validation" + rrjqbvValidator.validatorName + "Message",636rrjqbvValidator.message637);638setTimeout(function () {639if (640!$this.is(":focus") &&641$this.parents("form").first().data("jqbvIsSubmitting")642) {643rrjqbvThis.trigger("blur.validation");644} else {645rrjqbvThis.trigger("revalidate.validation");646}647}, 1);648}649}650);651}652return false;653},654},655ajax: {656name: "ajax",657init: function ($this, name) {658return {659validatorName: name,660url: $this.data("validation" + name + "Ajax"),661lastValue: $this.val(),662lastValid: true,663lastFinished: true,664};665},666validate: function ($this, value, validator) {667if (668"" + validator.lastValue === "" + value &&669validator.lastFinished === true670) {671return validator.lastValid === false;672}673if (validator.lastFinished === true) {674validator.lastValue = value;675validator.lastValid = true;676validator.lastFinished = false;677$.ajax({678url: validator.url,679data:680"value=" +681encodeURIComponent(value) +682"&field=" +683$this.attr("name"),684dataType: "json",685success: function (data) {686if ("" + validator.lastValue === "" + data.value) {687validator.lastValid = !!data.valid;688if (data.message) {689validator.message = data.message;690}691validator.lastFinished = true;692$this.data(693"validation" + validator.validatorName + "Message",694validator.message695);696setTimeout(function () {697$this.trigger("revalidate.validation");698}, 1);699}700},701failure: function () {702validator.lastValid = true;703validator.message = "ajax call failed";704validator.lastFinished = true;705$this.data(706"validation" + validator.validatorName + "Message",707validator.message708);709setTimeout(function () {710$this.trigger("revalidate.validation");711}, 1);712},713});714}715return false;716},717},718regex: {719name: "regex",720init: function ($this, name) {721var result = {};722var regexString = $this.data("validation" + name + "Regex");723result.regex = regexFromString(regexString);724if (regexString === undefined) {725$.error(726"Can't find regex for '" +727name +728"' validator on '" +729$this.attr("name") +730"'"731);732}733var message = "Not in the expected format";734if ($this.data("validation" + name + "Message")) {735message = $this.data("validation" + name + "Message");736}737result.message = message;738result.originalName = name;739return result;740},741validate: function ($this, value, validator) {742return (743(!validator.regex.test(value) && !validator.negative) ||744(validator.regex.test(value) && validator.negative)745);746},747},748email: {749name: "email",750init: function ($this, name) {751var result = {};752result.regex = regexFromString(753"[a-zA-Z0-9.!#$%&\u2019*+/=?^_`{|}~-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"754);755var message = "Not a valid email address";756if ($this.data("validation" + name + "Message")) {757message = $this.data("validation" + name + "Message");758}759result.message = message;760result.originalName = name;761return result;762},763validate: function ($this, value, validator) {764return (765(!validator.regex.test(value) && !validator.negative) ||766(validator.regex.test(value) && validator.negative)767);768},769},770required: {771name: "required",772init: function ($this, name) {773var message = "This is required";774if ($this.data("validation" + name + "Message")) {775message = $this.data("validation" + name + "Message");776}777return {778message: message,779includeEmpty: true,780};781},782validate: function ($this, value, validator) {783return !!(784(value.length === 0 && !validator.negative) ||785(value.length > 0 && validator.negative)786);787},788blockSubmit: true,789},790match: {791name: "match",792init: function ($this, name) {793var elementName = $this.data("validation" + name + "Match");794var $form = $this.parents("form").first();795var $element = $form.find('[name="' + elementName + '"]').first();796$element.bind("validation.validation", function () {797$this.trigger("revalidate.validation", {798submitting: true,799});800});801var result = {};802result.element = $element;803if ($element.length === 0) {804$.error(805"Can't find field '" +806elementName +807"' to match '" +808$this.attr("name") +809"' against in '" +810name +811"' validator"812);813}814var message = "Must match";815var $label = null;816if (817($label = $form.find('label[for="' + elementName + '"]')).length818) {819message += " '" + $label.text() + "'";820} else if (821($label = $element.parents(".form-group").first().find("label"))822.length823) {824message += " '" + $label.first().text() + "'";825}826if ($this.data("validation" + name + "Message")) {827message = $this.data("validation" + name + "Message");828}829result.message = message;830return result;831},832validate: function ($this, value, validator) {833return (834(value !== validator.element.val() && !validator.negative) ||835(value === validator.element.val() && validator.negative)836);837},838blockSubmit: true,839includeEmpty: true,840},841max: {842name: "max",843init: function ($this, name) {844var result = {};845result.max = $this.data("validation" + name + "Max");846result.message = "Too high: Maximum of '" + result.max + "'";847if ($this.data("validation" + name + "Message")) {848result.message = $this.data("validation" + name + "Message");849}850return result;851},852validate: function ($this, value, validator) {853return (854(parseFloat(value, 10) > parseFloat(validator.max, 10) &&855!validator.negative) ||856(parseFloat(value, 10) <= parseFloat(validator.max, 10) &&857validator.negative)858);859},860},861min: {862name: "min",863init: function ($this, name) {864var result = {};865result.min = $this.data("validation" + name + "Min");866result.message = "Too low: Minimum of '" + result.min + "'";867if ($this.data("validation" + name + "Message")) {868result.message = $this.data("validation" + name + "Message");869}870return result;871},872validate: function ($this, value, validator) {873return (874(parseFloat(value) < parseFloat(validator.min) &&875!validator.negative) ||876(parseFloat(value) >= parseFloat(validator.min) &&877validator.negative)878);879},880},881maxlength: {882name: "maxlength",883init: function ($this, name) {884var result = {};885result.maxlength = $this.data("validation" + name + "Maxlength");886result.message =887"Too long: Maximum of '" + result.maxlength + "' characters";888if ($this.data("validation" + name + "Message")) {889result.message = $this.data("validation" + name + "Message");890}891return result;892},893validate: function ($this, value, validator) {894return (895(value.length > validator.maxlength && !validator.negative) ||896(value.length <= validator.maxlength && validator.negative)897);898},899},900minlength: {901name: "minlength",902init: function ($this, name) {903var result = {};904result.minlength = $this.data("validation" + name + "Minlength");905result.message =906"Too short: Minimum of '" + result.minlength + "' characters";907if ($this.data("validation" + name + "Message")) {908result.message = $this.data("validation" + name + "Message");909}910return result;911},912validate: function ($this, value, validator) {913return (914(value.length < validator.minlength && !validator.negative) ||915(value.length >= validator.minlength && validator.negative)916);917},918},919maxchecked: {920name: "maxchecked",921init: function ($this, name) {922var result = {};923var elements = $this924.parents("form")925.first()926.find('[name="' + $this.attr("name") + '"]');927elements.bind("change.validation click.validation", function () {928$this.trigger("revalidate.validation", {929includeEmpty: true,930});931});932result.elements = elements;933result.maxchecked = $this.data("validation" + name + "Maxchecked");934var message = "Too many: Max '" + result.maxchecked + "' checked";935if ($this.data("validation" + name + "Message")) {936message = $this.data("validation" + name + "Message");937}938result.message = message;939return result;940},941validate: function ($this, value, validator) {942return (943(validator.elements.filter(":checked").length >944validator.maxchecked &&945!validator.negative) ||946(validator.elements.filter(":checked").length <=947validator.maxchecked &&948validator.negative)949);950},951blockSubmit: true,952},953minchecked: {954name: "minchecked",955init: function ($this, name) {956var result = {};957var elements = $this958.parents("form")959.first()960.find('[name="' + $this.attr("name") + '"]');961elements.bind("change.validation click.validation", function () {962$this.trigger("revalidate.validation", {963includeEmpty: true,964});965});966result.elements = elements;967result.minchecked = $this.data("validation" + name + "Minchecked");968var message = "Too few: Min '" + result.minchecked + "' checked";969if ($this.data("validation" + name + "Message")) {970message = $this.data("validation" + name + "Message");971}972result.message = message;973return result;974},975validate: function ($this, value, validator) {976return (977(validator.elements.filter(":checked").length <978validator.minchecked &&979!validator.negative) ||980(validator.elements.filter(":checked").length >=981validator.minchecked &&982validator.negative)983);984},985blockSubmit: true,986includeEmpty: true,987},988number: {989name: "number",990init: function ($this, name) {991var result = {};992result.step = 1;993if ($this.attr("step")) {994result.step = $this.attr("step");995}996if ($this.data("validation" + name + "Step")) {997result.step = $this.data("validation" + name + "Step");998}999result.decimal = ".";1000if ($this.data("validation" + name + "Decimal")) {1001result.decimal = $this.data("validation" + name + "Decimal");1002}1003result.thousands = "";1004if ($this.data("validation" + name + "Thousands")) {1005result.thousands = $this.data("validation" + name + "Thousands");1006}1007result.regex = regexFromString(1008"([+-]?\\d+(\\" + result.decimal + "\\d+)?)?"1009);1010result.message = "Must be a number";1011var dataMessage = $this.data("validation" + name + "Message");1012if (dataMessage) {1013result.message = dataMessage;1014}1015return result;1016},1017validate: function ($this, value, validator) {1018var globalValue = value1019.replace(validator.decimal, ".")1020.replace(validator.thousands, "");1021var multipliedValue = parseFloat(globalValue);1022var multipliedStep = parseFloat(validator.step);1023while (multipliedStep % 1 !== 0) {1024multipliedStep = parseFloat(multipliedStep.toPrecision(12)) * 10;1025multipliedValue = parseFloat(multipliedValue.toPrecision(12)) * 10;1026}1027var regexResult = validator.regex.test(value);1028var stepResult =1029parseFloat(multipliedValue) % parseFloat(multipliedStep) === 0;1030var typeResult =1031!isNaN(parseFloat(globalValue)) && isFinite(globalValue);1032var result = !(regexResult && stepResult && typeResult);1033return result;1034},1035message: "Must be a number",1036},1037},1038builtInValidators: {1039email: {1040name: "Email",1041type: "email",1042},1043passwordagain: {1044name: "Passwordagain",1045type: "match",1046match: "password",1047message:1048"Does not match the given password<!-- data-validator-paswordagain-message to override -->",1049},1050positive: {1051name: "Positive",1052type: "shortcut",1053shortcut: "number,positivenumber",1054},1055negative: {1056name: "Negative",1057type: "shortcut",1058shortcut: "number,negativenumber",1059},1060integer: {1061name: "Integer",1062type: "regex",1063regex: "[+-]?\\d+",1064message:1065"No decimal places allowed<!-- data-validator-integer-message to override -->",1066},1067positivenumber: {1068name: "Positivenumber",1069type: "min",1070min: 0,1071message:1072"Must be a positive number<!-- data-validator-positivenumber-message to override -->",1073},1074negativenumber: {1075name: "Negativenumber",1076type: "max",1077max: 0,1078message:1079"Must be a negative number<!-- data-validator-negativenumber-message to override -->",1080},1081required: {1082name: "Required",1083type: "required",1084message:1085"This is required<!-- data-validator-required-message to override -->",1086},1087checkone: {1088name: "Checkone",1089type: "minchecked",1090minchecked: 1,1091message:1092"Check at least one option<!-- data-validation-checkone-message to override -->",1093},1094number: {1095name: "Number",1096type: "number",1097decimal: ".",1098step: "1",1099},1100pattern: {1101name: "Pattern",1102type: "regex",1103message: "Not in expected format",1104},1105},1106};1107var formatValidatorName = function (name) {1108return name.toLowerCase().replace(/(^|\s)([a-z])/g, function (m, p1, p2) {1109return p1 + p2.toUpperCase();1110});1111};1112var getValue = function ($this) {1113var value = null;1114var type = $this.attr("type");1115if (type === "checkbox") {1116value = $this.is(":checked") ? value : "";1117var checkboxParent =1118$this.parents("form").first() || $this.parents(".form-group").first();1119if (checkboxParent) {1120value = checkboxParent1121.find("input[name='" + $this.attr("name") + "']:checked")1122.map(function (i, el) {1123return $(el).val();1124})1125.toArray()1126.join(",");1127}1128} else if (type === "radio") {1129value =1130$('input[name="' + $this.attr("name") + '"]:checked').length > 01131? $this.val()1132: "";1133var radioParent =1134$this.parents("form").first() || $this.parents(".form-group").first();1135if (radioParent) {1136value = radioParent1137.find("input[name='" + $this.attr("name") + "']:checked")1138.map(function (i, el) {1139return $(el).val();1140})1141.toArray()1142.join(",");1143}1144} else if (type === "number") {1145if ($this[0].validity.valid) {1146value = $this.val();1147} else {1148if ($this[0].validity.badInput || $this[0].validity.stepMismatch) {1149value = "NaN";1150} else {1151value = "";1152}1153}1154} else {1155value = $this.val();1156}1157return value;1158};1159
1160function regexFromString(inputstring) {1161return new RegExp("^" + inputstring + "$");1162}1163/**1164* Thanks to Jason Bunting via StackOverflow.com
1165*
1166* http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string#answer-359910
1167* Short link: http://tinyurl.com/executeFunctionByName
1168**/
1169function executeFunctionByName(functionName, context) {1170var args = Array.prototype.slice.call(arguments, 2);1171var namespaces = functionName.split(".");1172var func = namespaces.pop();1173for (var i = 0; i < namespaces.length; i++) {1174context = context[namespaces[i]];1175}1176return context[func].apply(context, args);1177}1178$.fn.jqBootstrapValidation = function (method) {1179if (defaults.methods[method]) {1180return defaults.methods[method].apply(1181this,1182Array.prototype.slice.call(arguments, 1)1183);1184} else if (typeof method === "object" || !method) {1185return defaults.methods.init.apply(this, arguments);1186} else {1187$.error(1188"Method " + method + " does not exist on jQuery.jqBootstrapValidation"1189);1190return null;1191}1192};1193$.jqBootstrapValidation = function (options) {1194$(":input")1195.not("[type=image],[type=submit]")1196.jqBootstrapValidation.apply(this, arguments);1197};1198})(jQuery);