| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768 |
- /*!
- * FormValidation (http://formvalidation.io)
- * The best jQuery plugin to validate form fields. Support Bootstrap, Foundation, Pure, SemanticUI, UIKit and custom frameworks
- *
- * This is a custom build that does NOT consist of all validators. Only popular validators are included:
- * - between
- * - callback
- * - choice
- * - color
- * - creditCard
- * - date
- * - different
- * - digits
- * - emailAddress
- * - file
- * - greaterThan
- * - identical
- * - integer
- * - lessThan
- * - notEmpty
- * - numeric
- * - promise
- * - regexp
- * - remote
- * - stringLength
- * - uri
- *
- * Use formValidation(.min).js file if you want to have all validators.
- *
- * @version v0.8.1, built on 2016-07-29 1:10:54 AM
- * @author https://twitter.com/formvalidation
- * @copyright (c) 2013 - 2016 Nguyen Huu Phuoc
- * @license http://formvalidation.io/license/
- */
- // Register the namespace
- window.FormValidation = {
- AddOn: {}, // Add-ons
- Framework: {}, // Supported frameworks
- I18n: {}, // i18n
- Validator: {} // Available validators
- };
- if (typeof jQuery === 'undefined') {
- throw new Error('FormValidation requires jQuery');
- }
- (function($) {
- var version = $.fn.jquery.split(' ')[0].split('.');
- if ((+version[0] < 2 && +version[1] < 9) || (+version[0] === 1 && +version[1] === 9 && +version[2] < 1)) {
- throw new Error('FormValidation requires jQuery version 1.9.1 or higher');
- }
- }(jQuery));
- (function($) {
- // TODO: Remove backward compatibility
- /**
- * Constructor
- *
- * @param {jQuery|String} form The form element or selector
- * @param {Object} options The options
- * @param {String} [namespace] The optional namespace which is used for data-{namespace}-xxx attributes and internal data.
- * Currently, it's used to support backward version
- * @constructor
- */
- FormValidation.Base = function(form, options, namespace) {
- this.$form = $(form);
- this.options = $.extend({}, $.fn.formValidation.DEFAULT_OPTIONS, options);
- this._namespace = namespace || 'fv';
- this.$invalidFields = $([]); // Array of invalid fields
- this.$submitButton = null; // The submit button which is clicked to submit form
- this.$hiddenButton = null;
- // Validating status
- this.STATUS_NOT_VALIDATED = 'NOT_VALIDATED';
- this.STATUS_VALIDATING = 'VALIDATING';
- this.STATUS_INVALID = 'INVALID';
- this.STATUS_VALID = 'VALID';
- this.STATUS_IGNORED = 'IGNORED';
- // Default message
- this.DEFAULT_MESSAGE = $.fn.formValidation.DEFAULT_MESSAGE;
- // Determine the event that is fired when user change the field value
- // Most modern browsers supports input event except IE 7, 8.
- // IE 9 supports input event but the event is still not fired if I press the backspace key.
- // Get IE version
- // https://gist.github.com/padolsey/527683/#comment-7595
- this._ieVersion = (function() {
- var v = 3, div = document.createElement('div'), a = div.all || [];
- while (div.innerHTML = '<!--[if gt IE '+(++v)+']><br><![endif]-->', a[0]) {}
- return v > 4 ? v : document.documentMode;
- }());
- var el = document.createElement('div');
- this._changeEvent = (this._ieVersion === 9 || !('oninput' in el)) ? 'keyup' : 'input';
- // The flag to indicate that the form is ready to submit when a remote/callback validator returns
- this._submitIfValid = null;
- // Field elements
- this._cacheFields = {};
- this._init();
- };
- FormValidation.Base.prototype = {
- constructor: FormValidation.Base,
- /**
- * Check if the number of characters of field value exceed the threshold or not
- *
- * @param {jQuery} $field The field element
- * @returns {Boolean}
- */
- _exceedThreshold: function($field) {
- var ns = this._namespace,
- field = $field.attr('data-' + ns + '-field'),
- threshold = this.options.fields[field].threshold || this.options.threshold;
- if (!threshold) {
- return true;
- }
- var cannotType = $.inArray($field.attr('type'), ['button', 'checkbox', 'file', 'hidden', 'image', 'radio', 'reset', 'submit']) !== -1;
- return (cannotType || $field.val().length >= threshold);
- },
- /**
- * Init form
- */
- _init: function() {
- var that = this,
- ns = this._namespace,
- options = {
- addOns: {},
- autoFocus: this.$form.attr('data-' + ns + '-autofocus'),
- button: {
- selector: this.$form.attr('data-' + ns + '-button-selector') || this.$form.attr('data-' + ns + '-submitbuttons'), // Support backward
- disabled: this.$form.attr('data-' + ns + '-button-disabled')
- },
- control: {
- valid: this.$form.attr('data-' + ns + '-control-valid'),
- invalid: this.$form.attr('data-' + ns + '-control-invalid')
- },
- err: {
- clazz: this.$form.attr('data-' + ns + '-err-clazz'),
- container: this.$form.attr('data-' + ns + '-err-container') || this.$form.attr('data-' + ns + '-container'), // Support backward
- parent: this.$form.attr('data-' + ns + '-err-parent')
- },
- events: {
- formInit: this.$form.attr('data-' + ns + '-events-form-init'),
- formPreValidate: this.$form.attr('data-' + ns + '-events-form-prevalidate'),
- formError: this.$form.attr('data-' + ns + '-events-form-error'),
- formReset: this.$form.attr('data-' + ns + '-events-form-reset'),
- formSuccess: this.$form.attr('data-' + ns + '-events-form-success'),
- fieldAdded: this.$form.attr('data-' + ns + '-events-field-added'),
- fieldRemoved: this.$form.attr('data-' + ns + '-events-field-removed'),
- fieldInit: this.$form.attr('data-' + ns + '-events-field-init'),
- fieldError: this.$form.attr('data-' + ns + '-events-field-error'),
- fieldReset: this.$form.attr('data-' + ns + '-events-field-reset'),
- fieldSuccess: this.$form.attr('data-' + ns + '-events-field-success'),
- fieldStatus: this.$form.attr('data-' + ns + '-events-field-status'),
- localeChanged: this.$form.attr('data-' + ns + '-events-locale-changed'),
- validatorError: this.$form.attr('data-' + ns + '-events-validator-error'),
- validatorSuccess: this.$form.attr('data-' + ns + '-events-validator-success'),
- validatorIgnored: this.$form.attr('data-' + ns + '-events-validator-ignored')
- },
- excluded: this.$form.attr('data-' + ns + '-excluded'),
- icon: {
- valid: this.$form.attr('data-' + ns + '-icon-valid') || this.$form.attr('data-' + ns + '-feedbackicons-valid'), // Support backward
- invalid: this.$form.attr('data-' + ns + '-icon-invalid') || this.$form.attr('data-' + ns + '-feedbackicons-invalid'), // Support backward
- validating: this.$form.attr('data-' + ns + '-icon-validating') || this.$form.attr('data-' + ns + '-feedbackicons-validating'), // Support backward
- feedback: this.$form.attr('data-' + ns + '-icon-feedback')
- },
- live: this.$form.attr('data-' + ns + '-live'),
- locale: this.$form.attr('data-' + ns + '-locale'),
- message: this.$form.attr('data-' + ns + '-message'),
- onPreValidate: this.$form.attr('data-' + ns + '-onprevalidate'),
- onError: this.$form.attr('data-' + ns + '-onerror'),
- onReset: this.$form.attr('data-' + ns + '-onreset'),
- onSuccess: this.$form.attr('data-' + ns + '-onsuccess'),
- row: {
- selector: this.$form.attr('data-' + ns + '-row-selector') || this.$form.attr('data-' + ns + '-group'), // Support backward
- valid: this.$form.attr('data-' + ns + '-row-valid'),
- invalid: this.$form.attr('data-' + ns + '-row-invalid'),
- feedback: this.$form.attr('data-' + ns + '-row-feedback')
- },
- threshold: this.$form.attr('data-' + ns + '-threshold'),
- trigger: this.$form.attr('data-' + ns + '-trigger'),
- verbose: this.$form.attr('data-' + ns + '-verbose'),
- fields: {}
- };
- this.$form
- // Disable client side validation in HTML 5
- .attr('novalidate', 'novalidate')
- .addClass(this.options.elementClass)
- // Disable the default submission first
- .on('submit.' + ns, function(e) {
- e.preventDefault();
- that.validate();
- })
- .on('click.' + ns, this.options.button.selector, function() {
- that.$submitButton = $(this);
- // The user just click the submit button
- that._submitIfValid = true;
- });
- if (this.options.declarative === true || this.options.declarative === 'true') {
- // Find all fields which have either "name" or "data-{namespace}-field" attribute
- this.$form
- .find('[name], [data-' + ns + '-field]')
- .each(function() {
- var $field = $(this),
- field = $field.attr('name') || $field.attr('data-' + ns + '-field'),
- opts = that._parseOptions($field);
- if (opts) {
- $field.attr('data-' + ns + '-field', field);
- options.fields[field] = $.extend({}, opts, options.fields[field]);
- }
- });
- }
- this.options = $.extend(true, this.options, options);
- // Normalize the err.parent option
- if ('string' === typeof this.options.err.parent) {
- this.options.err.parent = new RegExp(this.options.err.parent);
- }
- // Support backward
- if (this.options.container) {
- this.options.err.container = this.options.container;
- delete this.options.container;
- }
- if (this.options.feedbackIcons) {
- this.options.icon = $.extend(true, this.options.icon, this.options.feedbackIcons);
- delete this.options.feedbackIcons;
- }
- if (this.options.group) {
- this.options.row.selector = this.options.group;
- delete this.options.group;
- }
- if (this.options.submitButtons) {
- this.options.button.selector = this.options.submitButtons;
- delete this.options.submitButtons;
- }
- // If the locale is not found, reset it to default one
- if (!FormValidation.I18n[this.options.locale]) {
- this.options.locale = $.fn.formValidation.DEFAULT_OPTIONS.locale;
- }
- // Parse the add-on options from HTML attributes
- if (this.options.declarative === true || this.options.declarative === 'true') {
- this.options = $.extend(true, this.options, { addOns: this._parseAddOnOptions() });
- }
- // When pressing Enter on any field in the form, the first submit button will do its job.
- // The form then will be submitted.
- // I create a first hidden submit button
- this.$hiddenButton = $('<button/>')
- .attr('type', 'submit')
- .prependTo(this.$form)
- .addClass('fv-hidden-submit')
- .css({ display: 'none', width: 0, height: 0 });
- this.$form
- .on('click.' + this._namespace, '[type="submit"]', function(e) {
- // #746: Check if the button click handler returns false
- if (!e.isDefaultPrevented()) {
- var $target = $(e.target),
- // The button might contain HTML tag
- $button = $target.is('[type="submit"]') ? $target.eq(0) : $target.parent('[type="submit"]').eq(0);
- // Don't perform validation when clicking on the submit button/input which
- // aren't defined by the 'button.selector' option
- if (that.options.button.selector && !$button.is(that.options.button.selector) && !$button.is(that.$hiddenButton)) {
- that.$form.off('submit.' + that._namespace).submit();
- // Fix the issue where 'formnovalidate' causes IE to send two postbacks to server
- return false;
- }
- }
- });
- for (var field in this.options.fields) {
- this._initField(field);
- }
- // Init the add-ons
- for (var addOn in this.options.addOns) {
- if ('function' === typeof FormValidation.AddOn[addOn].init) {
- FormValidation.AddOn[addOn].init(this, this.options.addOns[addOn]);
- }
- }
- this.$form.trigger($.Event(this.options.events.formInit), {
- bv: this, // Support backward
- fv: this,
- options: this.options
- });
- // Prepare the events
- if (this.options.onPreValidate) {
- this.$form.on(this.options.events.formPreValidate, function(e) {
- FormValidation.Helper.call(that.options.onPreValidate, [e]);
- });
- }
- if (this.options.onSuccess) {
- this.$form.on(this.options.events.formSuccess, function(e) {
- FormValidation.Helper.call(that.options.onSuccess, [e]);
- });
- }
- if (this.options.onError) {
- this.$form.on(this.options.events.formError, function(e) {
- FormValidation.Helper.call(that.options.onError, [e]);
- });
- }
- if (this.options.onReset) {
- this.$form.on(this.options.events.formReset, function(e) {
- FormValidation.Helper.call(that.options.onReset, [e]);
- });
- }
- },
- /**
- * Init field
- *
- * @param {String|jQuery} field The field name or field element
- */
- _initField: function(field) {
- var ns = this._namespace,
- fields = $([]);
- switch (typeof field) {
- case 'object':
- fields = field;
- field = field.attr('data-' + ns + '-field');
- break;
- case 'string':
- fields = this.getFieldElements(field);
- fields.attr('data-' + ns + '-field', field);
- break;
- default:
- break;
- }
- // We don't need to validate non-existing fields
- if (fields.length === 0) {
- return;
- }
- if (this.options.fields[field] === null || this.options.fields[field].validators === null) {
- return;
- }
- var validators = this.options.fields[field].validators,
- validatorName,
- alias;
- for (validatorName in validators) {
- alias = validators[validatorName].alias || validatorName;
- if (!FormValidation.Validator[alias]) {
- delete this.options.fields[field].validators[validatorName];
- }
- }
- if (this.options.fields[field].enabled === null) {
- this.options.fields[field].enabled = true;
- }
- var that = this,
- total = fields.length,
- type = fields.attr('type'),
- updateAll = (total === 1) || ('radio' === type) || ('checkbox' === type),
- trigger = this._getFieldTrigger(fields.eq(0)),
- clazz = this.options.err.clazz.split(' ').join('.'),
- events = $.map(trigger, function(item) {
- return item + '.update.' + ns;
- }).join(' ');
- for (var i = 0; i < total; i++) {
- var $field = fields.eq(i),
- row = this.options.fields[field].row || this.options.row.selector,
- $parent = $field.closest(row),
- // Allow user to indicate where the error messages are shown
- // Support backward
- container = ('function' === typeof (this.options.fields[field].container || this.options.fields[field].err || this.options.err.container))
- ? (this.options.fields[field].container || this.options.fields[field].err || this.options.err.container).call(this, $field, this)
- : (this.options.fields[field].container || this.options.fields[field].err || this.options.err.container),
- $message = (container && container !== 'tooltip' && container !== 'popover') ? $(container) : this._getMessageContainer($field, row);
- if (container && container !== 'tooltip' && container !== 'popover') {
- $message.addClass(this.options.err.clazz);
- }
- // Remove all error messages and feedback icons
- $message.find('.' + clazz + '[data-' + ns + '-validator][data-' + ns + '-for="' + field + '"]').remove();
- $parent.find('i[data-' + ns + '-icon-for="' + field + '"]').remove();
- // Whenever the user change the field value, mark it as not validated yet
- $field.off(events).on(events, function() {
- that.updateStatus($(this), that.STATUS_NOT_VALIDATED);
- });
- // Create help block elements for showing the error messages
- $field.data(ns + '.messages', $message);
- for (validatorName in validators) {
- $field.data(ns + '.result.' + validatorName, this.STATUS_NOT_VALIDATED);
- if (!updateAll || i === total - 1) {
- $('<small/>')
- .css('display', 'none')
- .addClass(this.options.err.clazz)
- .attr('data-' + ns + '-validator', validatorName)
- .attr('data-' + ns + '-for', field)
- .attr('data-' + ns + '-result', this.STATUS_NOT_VALIDATED)
- .html(this._getMessage(field, validatorName))
- .appendTo($message);
- }
- // Init the validator
- alias = validators[validatorName].alias || validatorName;
- if ('function' === typeof FormValidation.Validator[alias].init) {
- FormValidation.Validator[alias].init(this, $field, this.options.fields[field].validators[validatorName], validatorName);
- }
- }
- // Prepare the feedback icons
- if (this.options.fields[field].icon !== false && this.options.fields[field].icon !== 'false'
- && this.options.icon
- && this.options.icon.valid && this.options.icon.invalid && this.options.icon.validating
- && (!updateAll || i === total - 1))
- {
- // $parent.removeClass(this.options.row.valid).removeClass(this.options.row.invalid).addClass(this.options.row.feedback);
- // Keep error messages which are populated from back-end
- $parent.addClass(this.options.row.feedback);
- var $icon = $('<i/>')
- .css('display', 'none')
- .addClass(this.options.icon.feedback)
- .attr('data-' + ns + '-icon-for', field)
- .insertAfter($field);
- // Store the icon as a data of field element
- (!updateAll ? $field : fields).data(ns + '.icon', $icon);
- if ('tooltip' === container || 'popover' === container) {
- (!updateAll ? $field : fields)
- .on(this.options.events.fieldError, function() {
- $parent.addClass('fv-has-tooltip');
- })
- .on(this.options.events.fieldSuccess, function() {
- $parent.removeClass('fv-has-tooltip');
- });
- $field
- // Show tooltip/popover message when field gets focus
- .off('focus.container.' + ns)
- .on('focus.container.' + ns, function() {
- that._showTooltip($(this), container);
- })
- // and hide them when losing focus
- .off('blur.container.' + ns)
- .on('blur.container.' + ns, function() {
- that._hideTooltip($(this), container);
- });
- }
- if ('string' === typeof this.options.fields[field].icon && this.options.fields[field].icon !== 'true') {
- $icon.appendTo($(this.options.fields[field].icon));
- } else {
- this._fixIcon($field, $icon);
- }
- }
- }
- // Sort the validators by priority
- var sortedByPriority = [];
- for (validatorName in validators) {
- alias = validators[validatorName].alias || validatorName;
- // Determine the priority
- validators[validatorName].priority = parseInt(validators[validatorName].priority
- || FormValidation.Validator[alias].priority
- || 1, 10);
- sortedByPriority.push({
- validator: validatorName,
- priority: validators[validatorName].priority
- });
- }
- sortedByPriority = sortedByPriority.sort(function(a, b) {
- return a.priority - b.priority;
- });
- // Prepare the events
- fields
- .data(ns + '.validators', sortedByPriority)
- .on(this.options.events.fieldSuccess, function(e, data) {
- var onSuccess = that.getOptions(data.field, null, 'onSuccess');
- if (onSuccess) {
- FormValidation.Helper.call(onSuccess, [e, data]);
- }
- })
- .on(this.options.events.fieldError, function(e, data) {
- var onError = that.getOptions(data.field, null, 'onError');
- if (onError) {
- FormValidation.Helper.call(onError, [e, data]);
- }
- })
- .on(this.options.events.fieldReset, function(e, data) {
- var onReset = that.getOptions(data.field, null, 'onReset');
- if (onReset) {
- FormValidation.Helper.call(onReset, [e, data]);
- }
- })
- .on(this.options.events.fieldStatus, function(e, data) {
- var onStatus = that.getOptions(data.field, null, 'onStatus');
- if (onStatus) {
- FormValidation.Helper.call(onStatus, [e, data]);
- }
- })
- .on(this.options.events.validatorError, function(e, data) {
- var onError = that.getOptions(data.field, data.validator, 'onError');
- if (onError) {
- FormValidation.Helper.call(onError, [e, data]);
- }
- })
- .on(this.options.events.validatorIgnored, function(e, data) {
- var onIgnored = that.getOptions(data.field, data.validator, 'onIgnored');
- if (onIgnored) {
- FormValidation.Helper.call(onIgnored, [e, data]);
- }
- })
- .on(this.options.events.validatorSuccess, function(e, data) {
- var onSuccess = that.getOptions(data.field, data.validator, 'onSuccess');
- if (onSuccess) {
- FormValidation.Helper.call(onSuccess, [e, data]);
- }
- });
- // Set live mode
- this.onLiveChange(fields, 'live', function() {
- if (that._exceedThreshold($(this))) {
- that.validateField($(this));
- }
- });
- fields.trigger($.Event(this.options.events.fieldInit), {
- bv: this, // Support backward
- fv: this,
- field: field,
- element: fields
- });
- },
- /**
- * Check if the field is excluded.
- * Returning true means that the field will not be validated
- *
- * @param {jQuery} $field The field element
- * @returns {Boolean}
- */
- _isExcluded: function($field) {
- var ns = this._namespace,
- excludedAttr = $field.attr('data-' + ns + '-excluded'),
- // I still need to check the 'name' attribute while initializing the field
- field = $field.attr('data-' + ns + '-field') || $field.attr('name');
- switch (true) {
- case (!!field && this.options.fields && this.options.fields[field] && (this.options.fields[field].excluded === 'true' || this.options.fields[field].excluded === true)):
- case (excludedAttr === 'true'):
- case (excludedAttr === ''):
- return true;
- case (!!field && this.options.fields && this.options.fields[field] && (this.options.fields[field].excluded === 'false' || this.options.fields[field].excluded === false)):
- case (excludedAttr === 'false'):
- return false;
- case (!!field && this.options.fields && this.options.fields[field] && 'function' === typeof this.options.fields[field].excluded):
- return this.options.fields[field].excluded.call(this, $field, this);
- case (!!field && this.options.fields && this.options.fields[field] && 'string' === typeof this.options.fields[field].excluded):
- case (excludedAttr):
- return FormValidation.Helper.call(this.options.fields[field].excluded, [$field, this]);
- default:
- if (this.options.excluded) {
- // Convert to array first
- if ('string' === typeof this.options.excluded) {
- this.options.excluded = $.map(this.options.excluded.split(','), function(item) {
- // Trim the spaces
- return $.trim(item);
- });
- }
- var length = this.options.excluded.length;
- for (var i = 0; i < length; i++) {
- if (('string' === typeof this.options.excluded[i] && $field.is(this.options.excluded[i]))
- || ('function' === typeof this.options.excluded[i] && this.options.excluded[i].call(this, $field, this) === true))
- {
- return true;
- }
- }
- }
- return false;
- }
- },
- /**
- * Get a field changed trigger event
- *
- * @param {jQuery} $field The field element
- * @returns {String[]} The event names triggered on field change
- */
- _getFieldTrigger: function($field) {
- var ns = this._namespace,
- trigger = $field.data(ns + '.trigger');
- if (trigger) {
- return trigger;
- }
- // IE10/11 auto fires input event of elements using the placeholder attribute
- // https://connect.microsoft.com/IE/feedback/details/856700/
- var type = $field.attr('type'),
- name = $field.attr('data-' + ns + '-field'),
- event = ('radio' === type || 'checkbox' === type || 'file' === type || 'SELECT' === $field.get(0).tagName)
- ? 'change'
- : (this._ieVersion >= 10 && $field.attr('placeholder') ? 'keyup' : this._changeEvent);
- trigger = ((this.options.fields[name] ? this.options.fields[name].trigger : null) || this.options.trigger || event).split(' ');
- // Since the trigger data is used many times, I need to cache it to use later
- $field.data(ns + '.trigger', trigger);
- return trigger;
- },
- /**
- * Get the error message for given field and validator
- *
- * @param {String} field The field name
- * @param {String} validatorName The validator name
- * @returns {String}
- */
- _getMessage: function(field, validatorName) {
- if (!this.options.fields[field] || !this.options.fields[field].validators) {
- return '';
- }
- var validators = this.options.fields[field].validators,
- alias = (validators[validatorName] && validators[validatorName].alias) ? validators[validatorName].alias : validatorName;
- if (!FormValidation.Validator[alias]) {
- return '';
- }
- switch (true) {
- case !!validators[validatorName].message:
- return validators[validatorName].message;
- case !!this.options.fields[field].message:
- return this.options.fields[field].message;
- case !!this.options.message:
- return this.options.message;
- case (!!FormValidation.I18n[this.options.locale] && !!FormValidation.I18n[this.options.locale][alias] && !!FormValidation.I18n[this.options.locale][alias]['default']):
- return FormValidation.I18n[this.options.locale][alias]['default'];
- default:
- return this.DEFAULT_MESSAGE;
- }
- },
- /**
- * Get the element to place the error messages
- *
- * @param {jQuery} $field The field element
- * @param {String} row
- * @returns {jQuery}
- */
- _getMessageContainer: function($field, row) {
- if (!this.options.err.parent) {
- throw new Error('The err.parent option is not defined');
- }
- var $parent = $field.parent();
- if ($parent.is(row)) {
- return $parent;
- }
- var cssClasses = $parent.attr('class');
- if (!cssClasses) {
- return this._getMessageContainer($parent, row);
- }
- if (this.options.err.parent.test(cssClasses)) {
- return $parent;
- }
- return this._getMessageContainer($parent, row);
- },
- /**
- * Parse the add-on options from HTML attributes
- *
- * @returns {Object}
- */
- _parseAddOnOptions: function() {
- var ns = this._namespace,
- names = this.$form.attr('data-' + ns + '-addons'),
- addOns = this.options.addOns || {};
- if (names) {
- names = names.replace(/\s/g, '').split(',');
- for (var i = 0; i < names.length; i++) {
- if (!addOns[names[i]]) {
- addOns[names[i]] = {};
- }
- }
- }
- // Try to parse each add-on options
- var addOn, attrMap, attr, option;
- for (addOn in addOns) {
- if (!FormValidation.AddOn[addOn]) {
- // Add-on is not found
- delete addOns[addOn];
- continue;
- }
- attrMap = FormValidation.AddOn[addOn].html5Attributes;
- if (attrMap) {
- for (attr in attrMap) {
- option = this.$form.attr('data-' + ns + '-addons-' + addOn.toLowerCase() + '-' + attr.toLowerCase());
- if (option) {
- addOns[addOn][attrMap[attr]] = option;
- }
- }
- }
- }
- return addOns;
- },
- /**
- * Parse the validator options from HTML attributes
- *
- * @param {jQuery} $field The field element
- * @returns {Object}
- */
- _parseOptions: function($field) {
- var ns = this._namespace,
- field = $field.attr('name') || $field.attr('data-' + ns + '-field'),
- validators = {},
- aliasAttr = new RegExp('^data-' + ns + '-([a-z]+)-alias$'),
- validatorSet = $.extend({}, FormValidation.Validator),
- validator,
- v, // Validator name
- attrName,
- enabled,
- optionName,
- optionAttrName,
- optionValue,
- html5AttrName,
- html5AttrMap;
- // Determine whether the alias validator is used by checking the data-fv-validator-alias attribute
- $.each($field.get(0).attributes, function(i, attribute) {
- if (attribute.value && aliasAttr.test(attribute.name)) {
- v = attribute.name.split('-')[2];
- if (validatorSet[attribute.value]) {
- validatorSet[v] = validatorSet[attribute.value];
- validatorSet[v].alias = attribute.value;
- }
- }
- });
- for (v in validatorSet) {
- validator = validatorSet[v];
- attrName = 'data-' + ns + '-' + v.toLowerCase(),
- enabled = $field.attr(attrName) + '';
- html5AttrMap = ('function' === typeof validator.enableByHtml5) ? validator.enableByHtml5($field) : null;
- if ((html5AttrMap && enabled !== 'false')
- || (html5AttrMap !== true && ('' === enabled || 'true' === enabled || attrName === enabled.toLowerCase())))
- {
- // Try to parse the options via attributes
- validator.html5Attributes = $.extend({}, {
- message: 'message',
- onerror: 'onError',
- onreset: 'onReset',
- onsuccess: 'onSuccess',
- priority: 'priority',
- transformer: 'transformer'
- }, validator.html5Attributes);
- validators[v] = $.extend({}, html5AttrMap === true ? {} : html5AttrMap, validators[v]);
- if (validator.alias) {
- validators[v].alias = validator.alias;
- }
- for (html5AttrName in validator.html5Attributes) {
- optionName = validator.html5Attributes[html5AttrName];
- optionAttrName = 'data-' + ns + '-' + v.toLowerCase() + '-' + html5AttrName;
- optionValue = $field.attr(optionAttrName);
- if (optionValue) {
- if ('true' === optionValue || optionAttrName === optionValue.toLowerCase()) {
- optionValue = true;
- } else if ('false' === optionValue) {
- optionValue = false;
- }
- validators[v][optionName] = optionValue;
- }
- }
- }
- }
- var opts = {
- autoFocus: $field.attr('data-' + ns + '-autofocus'),
- err: $field.attr('data-' + ns + '-err-container') || $field.attr('data-' + ns + '-container'), // Support backward
- enabled: $field.attr('data-' + ns + '-enabled'),
- excluded: $field.attr('data-' + ns + '-excluded'),
- icon: $field.attr('data-' + ns + '-icon') || $field.attr('data-' + ns + '-feedbackicons') || (this.options.fields && this.options.fields[field] ? this.options.fields[field].feedbackIcons : null), // Support backward
- message: $field.attr('data-' + ns + '-message'),
- onError: $field.attr('data-' + ns + '-onerror'),
- onReset: $field.attr('data-' + ns + '-onreset'),
- onStatus: $field.attr('data-' + ns + '-onstatus'),
- onSuccess: $field.attr('data-' + ns + '-onsuccess'),
- row: $field.attr('data-' + ns + '-row') || $field.attr('data-' + ns + '-group') || (this.options.fields && this.options.fields[field] ? this.options.fields[field].group : null), // Support backward
- selector: $field.attr('data-' + ns + '-selector'),
- threshold: $field.attr('data-' + ns + '-threshold'),
- transformer: $field.attr('data-' + ns + '-transformer'),
- trigger: $field.attr('data-' + ns + '-trigger'),
- verbose: $field.attr('data-' + ns + '-verbose'),
- validators: validators
- },
- emptyOptions = $.isEmptyObject(opts), // Check if the field options are set using HTML attributes
- emptyValidators = $.isEmptyObject(validators); // Check if the field validators are set using HTML attributes
- if (!emptyValidators || (!emptyOptions && this.options.fields && this.options.fields[field])) {
- //opts.validators = validators;
- return opts;
- } else {
- return null;
- }
- },
- /**
- * Called when all validations are completed
- */
- _submit: function() {
- var isValid = this.isValid();
- if (isValid === null) {
- return;
- }
- var eventType = isValid ? this.options.events.formSuccess : this.options.events.formError,
- e = $.Event(eventType);
- this.$form.trigger(e);
- // Call default handler
- // Check if whether the submit button is clicked
- if (this.$submitButton) {
- isValid ? this._onSuccess(e) : this._onError(e);
- }
- },
- // ~~~~~~
- // Events
- // ~~~~~~
- /**
- * The default handler of error.form.fv event.
- * It will be called when there is a invalid field
- *
- * @param {jQuery.Event} e The jQuery event object
- */
- _onError: function(e) {
- if (e.isDefaultPrevented()) {
- return;
- }
- if ('submitted' === this.options.live) {
- // Enable live mode
- this.options.live = 'enabled';
- var that = this;
- for (var field in this.options.fields) {
- (function(f) {
- var fields = that.getFieldElements(f);
- if (fields.length) {
- that.onLiveChange(fields, 'live', function() {
- if (that._exceedThreshold($(this))) {
- that.validateField($(this));
- }
- });
- }
- })(field);
- }
- }
- // Determined the first invalid field which will be focused on automatically
- var ns = this._namespace;
- for (var i = 0; i < this.$invalidFields.length; i++) {
- var $field = this.$invalidFields.eq(i),
- autoFocus = this.isOptionEnabled($field.attr('data-' + ns + '-field'), 'autoFocus');
- if (autoFocus) {
- // Focus the field
- $field.focus();
- break;
- }
- }
- },
- /**
- * Called after validating a field element
- *
- * @param {jQuery} $field The field element
- * @param {String} [validatorName] The validator name
- */
- _onFieldValidated: function($field, validatorName) {
- var ns = this._namespace,
- field = $field.attr('data-' + ns + '-field'),
- validators = this.options.fields[field].validators,
- counter = {},
- numValidators = 0,
- data = {
- bv: this, // Support backward
- fv: this,
- field: field,
- element: $field,
- validator: validatorName,
- result: $field.data(ns + '.response.' + validatorName)
- };
- // Trigger an event after given validator completes
- if (validatorName) {
- switch ($field.data(ns + '.result.' + validatorName)) {
- case this.STATUS_INVALID:
- $field.trigger($.Event(this.options.events.validatorError), data);
- break;
- case this.STATUS_VALID:
- $field.trigger($.Event(this.options.events.validatorSuccess), data);
- break;
- case this.STATUS_IGNORED:
- $field.trigger($.Event(this.options.events.validatorIgnored), data);
- break;
- default:
- break;
- }
- }
- counter[this.STATUS_NOT_VALIDATED] = 0;
- counter[this.STATUS_VALIDATING] = 0;
- counter[this.STATUS_INVALID] = 0;
- counter[this.STATUS_VALID] = 0;
- counter[this.STATUS_IGNORED] = 0;
- for (var v in validators) {
- if (validators[v].enabled === false) {
- continue;
- }
- numValidators++;
- var result = $field.data(ns + '.result.' + v);
- if (result) {
- counter[result]++;
- }
- }
- // The sum of valid fields now also include ignored fields
- if (counter[this.STATUS_VALID] + counter[this.STATUS_IGNORED] === numValidators) {
- // Remove from the list of invalid fields
- this.$invalidFields = this.$invalidFields.not($field);
- $field.trigger($.Event(this.options.events.fieldSuccess), data);
- }
- // If all validators are completed and there is at least one validator which doesn't pass
- else if ((counter[this.STATUS_NOT_VALIDATED] === 0 || !this.isOptionEnabled(field, 'verbose')) && counter[this.STATUS_VALIDATING] === 0 && counter[this.STATUS_INVALID] > 0) {
- // Add to the list of invalid fields
- this.$invalidFields = this.$invalidFields.add($field);
- $field.trigger($.Event(this.options.events.fieldError), data);
- }
- },
- /**
- * The default handler of success.form.fv event.
- * It will be called when all the fields are valid
- *
- * @param {jQuery.Event} e The jQuery event object
- */
- _onSuccess: function(e) {
- if (e.isDefaultPrevented()) {
- return;
- }
- // Submit the form
- this.disableSubmitButtons(true).defaultSubmit();
- },
- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- // Abstract methods
- // Need to be implemented by sub-class that supports specific framework
- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- /**
- * Specific framework might need to adjust the icon position
- *
- * @param {jQuery} $field The field element
- * @param {jQuery} $icon The icon element
- */
- _fixIcon: function($field, $icon) {
- },
- /**
- * Create a tooltip or popover
- * It will be shown when focusing on the field
- *
- * @param {jQuery} $field The field element
- * @param {String} message The message
- * @param {String} type Can be 'tooltip' or 'popover'
- */
- _createTooltip: function($field, message, type) {
- },
- /**
- * Destroy the tooltip or popover
- *
- * @param {jQuery} $field The field element
- * @param {String} type Can be 'tooltip' or 'popover'
- */
- _destroyTooltip: function($field, type) {
- },
- /**
- * Hide a tooltip or popover
- *
- * @param {jQuery} $field The field element
- * @param {String} type Can be 'tooltip' or 'popover'
- */
- _hideTooltip: function($field, type) {
- },
- /**
- * Show a tooltip or popover
- *
- * @param {jQuery} $field The field element
- * @param {String} type Can be 'tooltip' or 'popover'
- */
- _showTooltip: function($field, type) {
- },
- // ~~~~~~~~~~~~~~
- // Public methods
- // ~~~~~~~~~~~~~~
- /**
- * Submit the form using default submission.
- * It also does not perform any validations when submitting the form
- */
- defaultSubmit: function() {
- var ns = this._namespace;
- if (this.$submitButton) {
- // Create hidden input to send the submit buttons
- $('<input/>')
- .attr({
- 'type': 'hidden',
- name: this.$submitButton.attr('name')
- })
- .attr('data-' + ns + '-submit-hidden', '')
- .val(this.$submitButton.val())
- .appendTo(this.$form);
- }
- // Submit form
- this.$form.off('submit.' + ns).submit();
- },
- /**
- * Disable/enable submit buttons
- *
- * @param {Boolean} disabled Can be true or false
- * @returns {FormValidation.Base}
- */
- disableSubmitButtons: function(disabled) {
- if (!disabled) {
- this.$form
- .find(this.options.button.selector)
- .removeAttr('disabled')
- .removeClass(this.options.button.disabled);
- } else if (this.options.live !== 'disabled') {
- // Don't disable if the live validating mode is disabled
- this.$form
- .find(this.options.button.selector)
- .attr('disabled', 'disabled')
- .addClass(this.options.button.disabled);
- }
- return this;
- },
- /**
- * Retrieve the field elements by given name
- *
- * @param {String} field The field name
- * @returns {null|jQuery[]}
- */
- getFieldElements: function(field) {
- if (!this._cacheFields[field]) {
- if (this.options.fields[field] && this.options.fields[field].selector) {
- // Look for the field inside the form first
- var f = this.$form.find(this.options.fields[field].selector);
- // If not found, search in entire document
- this._cacheFields[field] = f.length ? f : $(this.options.fields[field].selector);
- } else {
- this._cacheFields[field] = this.$form.find('[name="' + field + '"]');
- }
- }
- return this._cacheFields[field];
- },
- /**
- * Get the field value after applying transformer
- *
- * @param {String|jQuery} field The field name or field element
- * @param {String} validatorName The validator name
- * @returns {String}
- */
- getFieldValue: function(field, validatorName) {
- var $field, ns = this._namespace;
- if ('string' === typeof field) {
- $field = this.getFieldElements(field);
- if ($field.length === 0) {
- return null;
- }
- } else {
- $field = field;
- field = $field.attr('data-' + ns + '-field');
- }
- if (!field || !this.options.fields[field]) {
- return $field.val();
- }
- var transformer = (this.options.fields[field].validators && this.options.fields[field].validators[validatorName]
- ? this.options.fields[field].validators[validatorName].transformer : null)
- || this.options.fields[field].transformer;
- return transformer ? FormValidation.Helper.call(transformer, [$field, validatorName, this]) : $field.val();
- },
- /**
- * Get the namespace
- *
- * @returns {String}
- */
- getNamespace: function() {
- return this._namespace;
- },
- /**
- * Get the field options
- *
- * @param {String|jQuery} [field] The field name or field element. If it is not set, the method returns the form options
- * @param {String} [validator] The name of validator. It null, the method returns form options
- * @param {String} [option] The option name
- * @return {String|Object}
- */
- getOptions: function(field, validator, option) {
- var ns = this._namespace;
- if (!field) {
- return option ? this.options[option] : this.options;
- }
- if ('object' === typeof field) {
- field = field.attr('data-' + ns + '-field');
- }
- if (!this.options.fields[field]) {
- return null;
- }
- var options = this.options.fields[field];
- if (!validator) {
- return option ? options[option] : options;
- }
- if (!options.validators || !options.validators[validator]) {
- return null;
- }
- return option ? options.validators[validator][option] : options.validators[validator];
- },
- /**
- * Get the validating result of field
- *
- * @param {String|jQuery} field The field name or field element
- * @param {String} validatorName The validator name
- * @returns {String} The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID', 'VALID' or 'IGNORED'
- */
- getStatus: function(field, validatorName) {
- var ns = this._namespace;
- switch (typeof field) {
- case 'object':
- return field.data(ns + '.result.' + validatorName);
- case 'string':
- /* falls through */
- default:
- return this.getFieldElements(field).eq(0).data(ns + '.result.' + validatorName);
- }
- },
- /**
- * Check whether or not a field option is enabled
- *
- * @param {String} field The field name
- * @param {String} option The option name, "verbose", "autoFocus", for example
- * @returns {Boolean}
- */
- isOptionEnabled: function(field, option) {
- if (this.options.fields[field] && (this.options.fields[field][option] === 'true' || this.options.fields[field][option] === true)) {
- return true;
- }
- if (this.options.fields[field] && (this.options.fields[field][option] === 'false' || this.options.fields[field][option] === false)) {
- return false;
- }
- return this.options[option] === 'true' || this.options[option] === true;
- },
- /**
- * Check the form validity
- *
- * @returns {Boolean|null} Returns one of three values
- * - true, if all fields are valid
- * - false, if there is one invalid field
- * - null, if there is at least one field which is not validated yet or being validated
- */
- isValid: function() {
- for (var field in this.options.fields) {
- var isValidField = this.isValidField(field);
- if (isValidField === null) {
- return null;
- }
- if (isValidField === false) {
- return false;
- }
- }
- return true;
- },
- /**
- * Check if all fields inside a given container are valid.
- * It's useful when working with a wizard-like such as tab, collapse
- *
- * @param {String|jQuery} container The container selector or element
- * @returns {Boolean|null} Returns one of three values
- * - true, if all fields inside the container are valid
- * - false, if there is one invalid field inside the container
- * - null, if the container consists of at least one field which is not validated yet or being validated
- */
- isValidContainer: function(container) {
- var that = this,
- ns = this._namespace,
- fields = [],
- $container = ('string' === typeof container) ? $(container) : container;
- if ($container.length === 0) {
- return true;
- }
- $container.find('[data-' + ns + '-field]').each(function() {
- var $field = $(this);
- if (!that._isExcluded($field)) {
- fields.push($field);
- }
- });
- var total = fields.length,
- clazz = this.options.err.clazz.split(' ').join('.');
- for (var i = 0; i < total; i++) {
- var $f = fields[i],
- field = $f.attr('data-' + ns + '-field'),
- $errors = $f.data(ns + '.messages')
- .find('.' + clazz + '[data-' + ns + '-validator][data-' + ns + '-for="' + field + '"]');
- if (this.options.fields && this.options.fields[field]
- && (this.options.fields[field].enabled === 'false' || this.options.fields[field].enabled === false))
- {
- continue;
- }
- if ($errors.filter('[data-' + ns + '-result="' + this.STATUS_INVALID + '"]').length > 0) {
- return false;
- }
- // If the field is not validated
- if ($errors.filter('[data-' + ns + '-result="' + this.STATUS_NOT_VALIDATED + '"]').length > 0
- || $errors.filter('[data-' + ns + '-result="' + this.STATUS_VALIDATING + '"]').length > 0)
- {
- return null;
- }
- }
- return true;
- },
- /**
- * Check if the field is valid or not
- *
- * @param {String|jQuery} field The field name or field element
- * @returns {Boolean|null} Returns one of three values
- * - true, if the field passes all validators
- * - false, if the field doesn't pass any validator
- * - null, if there is at least one validator which isn't validated yet or being validated
- */
- isValidField: function(field) {
- var ns = this._namespace,
- fields = $([]);
- switch (typeof field) {
- case 'object':
- fields = field;
- field = field.attr('data-' + ns + '-field');
- break;
- case 'string':
- fields = this.getFieldElements(field);
- break;
- default:
- break;
- }
- if (fields.length === 0 || !this.options.fields[field]
- || this.options.fields[field].enabled === 'false' || this.options.fields[field].enabled === false)
- {
- return true;
- }
- var type = fields.attr('type'),
- total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length,
- $field, validatorName, status;
- for (var i = 0; i < total; i++) {
- $field = fields.eq(i);
- if (this._isExcluded($field)) {
- continue;
- }
- for (validatorName in this.options.fields[field].validators) {
- if (this.options.fields[field].validators[validatorName].enabled === false) {
- continue;
- }
- status = $field.data(ns + '.result.' + validatorName);
- if (status === this.STATUS_VALIDATING || status === this.STATUS_NOT_VALIDATED) {
- return null;
- } else if (status === this.STATUS_INVALID) {
- return false;
- }
- }
- }
- return true;
- },
- /**
- * Detach a handler function for a field live change event
- *
- * @param {jQuery[]} $fields The field elements
- * @param {String} namespace The event namespace
- * @returns {FormValidation.Base}
- */
- offLiveChange: function($fields, namespace) {
- if ($fields === null || $fields.length === 0) {
- return this;
- }
- var ns = this._namespace,
- trigger = this._getFieldTrigger($fields.eq(0)),
- events = $.map(trigger, function(item) {
- return item + '.' + namespace + '.' + ns;
- }).join(' ');
- $fields.off(events);
- return this;
- },
- /**
- * Attach a handler function for a field live change event
- *
- * @param {jQuery[]} $fields The field elements
- * @param {String} namespace The event namespace
- * @param {Function} handler The handler function
- * @returns {FormValidation.Base}
- */
- onLiveChange: function($fields, namespace, handler) {
- if ($fields === null || $fields.length === 0) {
- return this;
- }
- var ns = this._namespace,
- trigger = this._getFieldTrigger($fields.eq(0)),
- events = $.map(trigger, function(item) {
- return item + '.' + namespace + '.' + ns;
- }).join(' ');
- switch (this.options.live) {
- case 'submitted':
- break;
- case 'disabled':
- $fields.off(events);
- break;
- case 'enabled':
- /* falls through */
- default:
- $fields.off(events).on(events, function(e) {
- handler.apply(this, arguments);
- });
- break;
- }
- return this;
- },
- /**
- * Update the error message
- *
- * @param {String|jQuery} field The field name or field element
- * @param {String} validator The validator name
- * @param {String} message The message
- * @returns {FormValidation.Base}
- */
- updateMessage: function(field, validator, message) {
- var ns = this._namespace,
- $fields = $([]);
- switch (typeof field) {
- case 'object':
- $fields = field;
- field = field.attr('data-' + ns + '-field');
- break;
- case 'string':
- $fields = this.getFieldElements(field);
- break;
- default:
- break;
- }
- var clazz = this.options.err.clazz.split(' ').join('.');
- $fields.each(function() {
- $(this)
- .data(ns + '.messages')
- .find('.' + clazz + '[data-' + ns + '-validator="' + validator + '"][data-' + ns + '-for="' + field + '"]').html(message);
- });
- return this;
- },
- /**
- * Update all validating results of field
- *
- * @param {String|jQuery} field The field name or field element
- * @param {String} status The status. Can be 'NOT_VALIDATED', 'VALIDATING', 'INVALID', 'VALID' or 'IGNORED'
- * @param {String} [validatorName] The validator name. If null, the method updates validity result for all validators
- * @returns {FormValidation.Base}
- */
- updateStatus: function(field, status, validatorName) {
- var ns = this._namespace,
- fields = $([]);
- switch (typeof field) {
- case 'object':
- fields = field;
- field = field.attr('data-' + ns + '-field');
- break;
- case 'string':
- fields = this.getFieldElements(field);
- break;
- default:
- break;
- }
- if (!field || !this.options.fields[field]) {
- return this;
- }
- if (status === this.STATUS_NOT_VALIDATED) {
- // Reset the flag
- // To prevent the form from doing submit when a deferred validator returns true while typing
- this._submitIfValid = false;
- }
- var that = this,
- type = fields.attr('type'),
- row = this.options.fields[field].row || this.options.row.selector,
- total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length,
- clazz = this.options.err.clazz.split(' ').join('.');
- for (var i = 0; i < total; i++) {
- var $field = fields.eq(i);
- if (this._isExcluded($field)) {
- continue;
- }
- var $parent = $field.closest(row),
- $message = $field.data(ns + '.messages'),
- $allErrors = $message.find('.' + clazz + '[data-' + ns + '-validator][data-' + ns + '-for="' + field + '"]'),
- $errors = validatorName ? $allErrors.filter('[data-' + ns + '-validator="' + validatorName + '"]') : $allErrors,
- $icon = $field.data(ns + '.icon'),
- // Support backward
- container = ('function' === typeof (this.options.fields[field].container || this.options.fields[field].err || this.options.err.container))
- ? (this.options.fields[field].container || this.options.fields[field].err || this.options.err.container).call(this, $field, this)
- : (this.options.fields[field].container || this.options.fields[field].err || this.options.err.container),
- isValidField = null,
- isValidating,
- isNotValidated;
- // Update status
- if (validatorName) {
- $field.data(ns + '.result.' + validatorName, status);
- } else {
- for (var v in this.options.fields[field].validators) {
- $field.data(ns + '.result.' + v, status);
- }
- }
- // Show/hide error elements and feedback icons
- $errors.attr('data-' + ns + '-result', status);
- switch (status) {
- case this.STATUS_VALIDATING:
- isValidField = null;
- this.disableSubmitButtons(true);
- $field.removeClass(this.options.control.valid).removeClass(this.options.control.invalid);
- $parent.removeClass(this.options.row.valid).removeClass(this.options.row.invalid);
- if ($icon) {
- $icon.removeClass(this.options.icon.valid).removeClass(this.options.icon.invalid).addClass(this.options.icon.validating).show();
- }
- break;
- case this.STATUS_INVALID:
- isValidField = false;
- this.disableSubmitButtons(true);
- $field.removeClass(this.options.control.valid).addClass(this.options.control.invalid);
- $parent.removeClass(this.options.row.valid).addClass(this.options.row.invalid);
- if ($icon) {
- $icon.removeClass(this.options.icon.valid).removeClass(this.options.icon.validating).addClass(this.options.icon.invalid).show();
- }
- break;
- case this.STATUS_IGNORED: // Treat ignored fields like they are valid with some specialties
- case this.STATUS_VALID:
- isValidating = ($allErrors.filter('[data-' + ns + '-result="' + this.STATUS_VALIDATING +'"]').length > 0);
- isNotValidated = ($allErrors.filter('[data-' + ns + '-result="' + this.STATUS_NOT_VALIDATED +'"]').length > 0);
- var numIgnored = $allErrors.filter('[data-' + ns + '-result="' + this.STATUS_IGNORED +'"]').length;
- // If the field is valid (passes all validators)
- isValidField = (isValidating || isNotValidated) // There are some validators that have not done
- ? null
- // All validators are completed
- : ($allErrors.filter('[data-' + ns + '-result="' + this.STATUS_VALID +'"]').length + numIgnored === $allErrors.length);
- $field.removeClass(this.options.control.valid).removeClass(this.options.control.invalid);
- if (isValidField === true) {
- this.disableSubmitButtons(this.isValid() === false);
- if (status === this.STATUS_VALID) {
- $field.addClass(this.options.control.valid);
- }
- } else if (isValidField === false) {
- this.disableSubmitButtons(true);
- if (status === this.STATUS_VALID) {
- $field.addClass(this.options.control.invalid);
- }
- }
- if ($icon) {
- $icon.removeClass(this.options.icon.invalid).removeClass(this.options.icon.validating).removeClass(this.options.icon.valid);
- if (status === this.STATUS_VALID || numIgnored !== $allErrors.length) {
- $icon.addClass(isValidating
- ? this.options.icon.validating
- : (isValidField === null ? '' : (isValidField ? this.options.icon.valid : this.options.icon.invalid)))
- .show();
- }
- }
- var isValidContainer = this.isValidContainer($parent);
- if (isValidContainer !== null) {
- $parent.removeClass(this.options.row.valid).removeClass(this.options.row.invalid);
- if (status === this.STATUS_VALID || numIgnored !== $allErrors.length) {
- $parent.addClass(isValidContainer ? this.options.row.valid : this.options.row.invalid);
- }
- }
- break;
- case this.STATUS_NOT_VALIDATED:
- /* falls through */
- default:
- isValidField = null;
- this.disableSubmitButtons(false);
- $field.removeClass(this.options.control.valid).removeClass(this.options.control.invalid);
- $parent.removeClass(this.options.row.valid).removeClass(this.options.row.invalid);
- if ($icon) {
- $icon.removeClass(this.options.icon.valid).removeClass(this.options.icon.invalid).removeClass(this.options.icon.validating).hide();
- }
- break;
- }
- if ($icon && ('tooltip' === container || 'popover' === container)) {
- (isValidField === false)
- // Only show the first error message
- ? this._createTooltip($field, $allErrors.filter('[data-' + ns + '-result="' + that.STATUS_INVALID + '"]').eq(0).html(), container)
- : this._destroyTooltip($field, container);
- } else {
- (status === this.STATUS_INVALID) ? $errors.show() : $errors.hide();
- }
- // Trigger an event
- $field.trigger($.Event(this.options.events.fieldStatus), {
- bv: this, // Support backward
- fv: this,
- field: field,
- element: $field,
- status: status,
- validator: validatorName
- });
- this._onFieldValidated($field, validatorName);
- }
- return this;
- },
- /**
- * Validate the form
- *
- * @returns {FormValidation.Base}
- */
- validate: function() {
- if ($.isEmptyObject(this.options.fields)) {
- this._submit();
- return this;
- }
- this.$form.trigger($.Event(this.options.events.formPreValidate));
- this.disableSubmitButtons(true);
- this._submitIfValid = false;
- for (var field in this.options.fields) {
- this.validateField(field);
- }
- this._submit();
- this._submitIfValid = true;
- return this;
- },
- /**
- * Validate given field
- *
- * @param {String|jQuery} field The field name or field element
- * @returns {FormValidation.Base}
- */
- validateField: function(field) {
- var ns = this._namespace,
- fields = $([]);
- switch (typeof field) {
- case 'object':
- fields = field;
- field = field.attr('data-' + ns + '-field');
- break;
- case 'string':
- fields = this.getFieldElements(field);
- break;
- default:
- break;
- }
- if (fields.length === 0 || !this.options.fields[field]
- || this.options.fields[field].enabled === 'false' || this.options.fields[field].enabled === false)
- {
- return this;
- }
- var that = this,
- type = fields.attr('type'),
- total = (('radio' === type || 'checkbox' === type) && this.options.live !== 'disabled') ? 1 : fields.length,
- updateAll = ('radio' === type || 'checkbox' === type),
- validators = this.options.fields[field].validators,
- verbose = this.isOptionEnabled(field, 'verbose'),
- validatorName,
- alias,
- validateResult;
- for (var i = 0; i < total; i++) {
- var $field = fields.eq(i);
- if (this._isExcluded($field)) {
- continue;
- }
- var stop = false,
- sortedByPriority = $field.data(ns + '.validators'),
- numValidators = sortedByPriority.length;
- for (var j = 0; j < numValidators; j++) {
- validatorName = sortedByPriority[j].validator;
- if ($field.data(ns + '.dfs.' + validatorName)) {
- $field.data(ns + '.dfs.' + validatorName).reject();
- }
- if (stop) {
- break;
- }
- // Don't validate field if it is already done
- var result = $field.data(ns + '.result.' + validatorName);
- if (result === this.STATUS_VALID || result === this.STATUS_INVALID) {
- this._onFieldValidated($field, validatorName);
- continue;
- } else if (validators[validatorName].enabled === false) {
- // Changed in v0.6.2:
- // When the field validator is disabled, it should be treated as STATUS_IGNORED instead of STATUS_VALID
- // By doing that, the field with only disabled and ignored validators will not have success/error class
- this.updateStatus(updateAll ? field : $field, this.STATUS_IGNORED, validatorName);
- continue;
- }
- $field.data(ns + '.result.' + validatorName, this.STATUS_VALIDATING);
- // Check whether or not the validator is just an alias of another
- alias = validators[validatorName].alias || validatorName;
- validateResult = FormValidation.Validator[alias].validate(this, $field, validators[validatorName], validatorName);
- // validateResult can be a $.Deferred object ...
- if ('object' === typeof validateResult && validateResult.resolve) {
- this.updateStatus(updateAll ? field : $field, this.STATUS_VALIDATING, validatorName);
- $field.data(ns + '.dfs.' + validatorName, validateResult);
- validateResult.done(function($f, v, response) {
- // v is validator name
- $f.removeData(ns + '.dfs.' + v).data(ns + '.response.' + v, response);
- if (response.message) {
- that.updateMessage($f, v, response.message);
- }
- that.updateStatus(updateAll ? $f.attr('data-' + ns + '-field') : $f,
- response.valid === true ? that.STATUS_VALID : (response.valid === false ? that.STATUS_INVALID : that.STATUS_IGNORED),
- v);
- if (response.valid && that._submitIfValid === true) {
- // If a remote validator returns true and the form is ready to submit, then do it
- that._submit();
- } else if (response.valid === false && !verbose) {
- stop = true;
- }
- });
- }
- // ... or object { valid: true/false/null, message: 'dynamic message', otherKey: value, ... }
- else if ('object' === typeof validateResult && validateResult.valid !== undefined) {
- $field.data(ns + '.response.' + validatorName, validateResult);
- if (validateResult.message) {
- this.updateMessage(updateAll ? field : $field, validatorName, validateResult.message);
- }
- this.updateStatus(updateAll ? field : $field,
- validateResult.valid === true ? this.STATUS_VALID : (validateResult.valid === false ? this.STATUS_INVALID : this.STATUS_IGNORED),
- validatorName);
- if (validateResult.valid === false && !verbose) {
- break;
- }
- }
- // ... or a boolean value
- else if ('boolean' === typeof validateResult) {
- $field.data(ns + '.response.' + validatorName, validateResult);
- this.updateStatus(updateAll ? field : $field, validateResult ? this.STATUS_VALID : this.STATUS_INVALID, validatorName);
- if (!validateResult && !verbose) {
- break;
- }
- }
- // ... or null
- // to indicate that the field should be ignored for current validator
- else if (null === validateResult) {
- $field.data(ns + '.response.' + validatorName, validateResult);
- this.updateStatus(updateAll ? field : $field, this.STATUS_IGNORED, validatorName);
- }
- }
- }
- return this;
- },
- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- // Useful APIs which aren't used internally
- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- /**
- * Add a new field
- *
- * @param {String|jQuery} field The field name or field element
- * @param {Object} [options] The validator rules
- * @returns {FormValidation.Base}
- */
- addField: function(field, options) {
- var ns = this._namespace,
- fields = $([]);
- switch (typeof field) {
- case 'object':
- fields = field;
- field = field.attr('data-' + ns + '-field') || field.attr('name');
- break;
- case 'string':
- delete this._cacheFields[field];
- fields = this.getFieldElements(field);
- break;
- default:
- break;
- }
- fields.attr('data-' + ns + '-field', field);
- var type = fields.attr('type'),
- total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length;
- for (var i = 0; i < total; i++) {
- var $field = fields.eq(i);
- // Try to parse the options from HTML attributes
- var opts = this._parseOptions($field);
- opts = (opts === null) ? options : $.extend(true, opts, options);
- this.options.fields[field] = $.extend(true, this.options.fields[field], opts);
- // Update the cache
- this._cacheFields[field] = this._cacheFields[field] ? this._cacheFields[field].add($field) : $field;
- // Init the element
- this._initField(('checkbox' === type || 'radio' === type) ? field : $field);
- }
- this.disableSubmitButtons(false);
- // Trigger an event
- this.$form.trigger($.Event(this.options.events.fieldAdded), {
- field: field,
- element: fields,
- options: this.options.fields[field]
- });
- return this;
- },
- /**
- * Destroy the plugin
- * It will remove all error messages, feedback icons and turn off the events
- */
- destroy: function() {
- var ns = this._namespace, i, field, fields, $field, validator, $icon, row, alias;
- // Destroy the validators first
- for (field in this.options.fields) {
- fields = this.getFieldElements(field);
- for (i = 0; i < fields.length; i++) {
- $field = fields.eq(i);
- for (validator in this.options.fields[field].validators) {
- if ($field.data(ns + '.dfs.' + validator)) {
- $field.data(ns + '.dfs.' + validator).reject();
- }
- $field.removeData(ns + '.result.' + validator)
- .removeData(ns + '.response.' + validator)
- .removeData(ns + '.dfs.' + validator);
- // Destroy the validator
- alias = this.options.fields[field].validators[validator].alias || validator;
- if ('function' === typeof FormValidation.Validator[alias].destroy) {
- FormValidation.Validator[alias].destroy(this, $field, this.options.fields[field].validators[validator], validator);
- }
- }
- }
- }
- // Remove messages and icons
- var clazz = this.options.err.clazz.split(' ').join('.');
- for (field in this.options.fields) {
- fields = this.getFieldElements(field);
- row = this.options.fields[field].row || this.options.row.selector;
- for (i = 0; i < fields.length; i++) {
- $field = fields.eq(i);
- // Remove all error messages
- var $messages = $field.data(ns + '.messages');
- if ($messages) {
- $messages.find('.' + clazz + '[data-' + ns + '-validator][data-' + ns + '-for="' + field + '"]').remove();
- }
- $field
- .removeData(ns + '.messages')
- .removeData(ns + '.validators')
- // Remove feedback classes
- .closest(row)
- .removeClass(this.options.row.valid)
- .removeClass(this.options.row.invalid)
- .removeClass(this.options.row.feedback)
- .end()
- // Turn off events
- .off('.' + ns)
- .removeAttr('data-' + ns + '-field');
- // Remove feedback icons, tooltip/popover container
- // Support backward
- var container = ('function' === typeof (this.options.fields[field].container || this.options.fields[field].err || this.options.err.container))
- ? (this.options.fields[field].container || this.options.fields[field].err || this.options.err.container).call(this, $field, this)
- : (this.options.fields[field].container || this.options.fields[field].err || this.options.err.container);
- if ('tooltip' === container || 'popover' === container) {
- this._destroyTooltip($field, container);
- }
- $icon = $field.data(ns + '.icon');
- if ($icon) {
- $icon.remove();
- }
- $field.removeData(ns + '.icon')
- // It's safe to remove trigger data here, because it might be used when destroying the validator
- .removeData(ns + '.trigger');
- }
- }
- // Destroy the add-ons
- for (var addOn in this.options.addOns) {
- if ('function' === typeof FormValidation.AddOn[addOn].destroy) {
- FormValidation.AddOn[addOn].destroy(this, this.options.addOns[addOn]);
- }
- }
- this.disableSubmitButtons(false); // Enable submit buttons
- this.$hiddenButton.remove(); // Remove the hidden button
- this.$form
- .removeClass(this.options.elementClass)
- .off('.' + ns)
- .removeData('bootstrapValidator') // Support backward
- .removeData('formValidation')
- // Remove generated hidden elements
- .find('[data-' + ns + '-submit-hidden]').remove().end()
- .find('[type="submit"]')
- .off('click.' + ns);
- },
- /**
- * Enable/Disable all validators to given field
- *
- * @param {String} field The field name
- * @param {Boolean} enabled Enable/Disable field validators
- * @param {String} [validatorName] The validator name. If null, all validators will be enabled/disabled
- * @returns {FormValidation.Base}
- */
- enableFieldValidators: function(field, enabled, validatorName) {
- var validators = this.options.fields[field].validators;
- // Enable/disable particular validator
- if (validatorName
- && validators
- && validators[validatorName] && validators[validatorName].enabled !== enabled)
- {
- this.options.fields[field].validators[validatorName].enabled = enabled;
- this.updateStatus(field, this.STATUS_NOT_VALIDATED, validatorName);
- }
- // Enable/disable all validators
- else if (!validatorName && this.options.fields[field].enabled !== enabled) {
- this.options.fields[field].enabled = enabled;
- for (var v in validators) {
- this.enableFieldValidators(field, enabled, v);
- }
- }
- return this;
- },
- /**
- * Some validators have option which its value is dynamic.
- * For example, the zipCode validator has the country option which might be changed dynamically by a select element.
- *
- * @param {jQuery|String} field The field name or element
- * @param {String|Function} option The option which can be determined by:
- * - a string
- * - name of field which defines the value
- * - name of function which returns the value
- * - a function returns the value
- *
- * The callback function has the format of
- * callback: function(value, validator, $field) {
- * // value is the value of field
- * // validator is the BootstrapValidator instance
- * // $field is the field element
- * }
- *
- * @returns {String}
- */
- getDynamicOption: function(field, option) {
- var $field = ('string' === typeof field) ? this.getFieldElements(field) : field,
- value = $field.val();
- // Option can be determined by
- // ... a function
- if ('function' === typeof option) {
- return FormValidation.Helper.call(option, [value, this, $field]);
- }
- // ... value of other field
- else if ('string' === typeof option) {
- var $f = this.getFieldElements(option);
- if ($f.length) {
- return $f.val();
- }
- // ... return value of callback
- else {
- return FormValidation.Helper.call(option, [value, this, $field]) || option;
- }
- }
- return null;
- },
- /**
- * Get the form element
- *
- * @returns {jQuery}
- */
- getForm: function() {
- return this.$form;
- },
- /**
- * Get the list of invalid fields
- *
- * @returns {jQuery[]}
- */
- getInvalidFields: function() {
- return this.$invalidFields;
- },
- /**
- * Get the current locale
- *
- * @return {String}
- */
- getLocale: function() {
- return this.options.locale;
- },
- /**
- * Get the error messages
- *
- * @param {String|jQuery} [field] The field name or field element
- * If the field is not defined, the method returns all error messages of all fields
- * @param {String} [validator] The name of validator
- * If the validator is not defined, the method returns error messages of all validators
- * @returns {String[]}
- */
- getMessages: function(field, validator) {
- var that = this,
- ns = this._namespace,
- messages = [],
- $fields = $([]);
- switch (true) {
- case (field && 'object' === typeof field):
- $fields = field;
- break;
- case (field && 'string' === typeof field):
- var f = this.getFieldElements(field);
- if (f.length > 0) {
- var type = f.attr('type');
- $fields = ('radio' === type || 'checkbox' === type) ? f.eq(0) : f;
- }
- break;
- default:
- $fields = this.$invalidFields;
- break;
- }
- var filter = validator ? '[data-' + ns + '-validator="' + validator + '"]' : '',
- clazz = this.options.err.clazz.split(' ').join('.');
- $fields.each(function() {
- messages = messages.concat(
- $(this)
- .data(ns + '.messages')
- .find('.' + clazz + '[data-' + ns + '-for="' + $(this).attr('data-' + ns + '-field') + '"][data-' + ns + '-result="' + that.STATUS_INVALID + '"]' + filter)
- .map(function() {
- var v = $(this).attr('data-' + ns + '-validator'),
- f = $(this).attr('data-' + ns + '-for');
- return (that.options.fields[f].validators[v].enabled === false) ? '' : $(this).html();
- })
- .get()
- );
- });
- return messages;
- },
- /**
- * Returns the clicked submit button
- *
- * @returns {jQuery}
- */
- getSubmitButton: function() {
- return this.$submitButton;
- },
- /**
- * Remove a given field
- *
- * @param {String|jQuery} field The field name or field element
- * @returns {FormValidation.Base}
- */
- removeField: function(field) {
- var ns = this._namespace,
- fields = $([]);
- switch (typeof field) {
- case 'object':
- fields = field;
- field = field.attr('data-' + ns + '-field') || field.attr('name');
- fields.attr('data-' + ns + '-field', field);
- break;
- case 'string':
- fields = this.getFieldElements(field);
- break;
- default:
- break;
- }
- if (fields.length === 0) {
- return this;
- }
- var type = fields.attr('type'),
- total = ('radio' === type || 'checkbox' === type) ? 1 : fields.length;
- for (var i = 0; i < total; i++) {
- var $field = fields.eq(i);
- // Remove from the list of invalid fields
- this.$invalidFields = this.$invalidFields.not($field);
- // Update the cache
- this._cacheFields[field] = this._cacheFields[field].not($field);
- }
- if (!this._cacheFields[field] || this._cacheFields[field].length === 0) {
- delete this.options.fields[field];
- }
- if ('checkbox' === type || 'radio' === type) {
- this._initField(field);
- }
- this.disableSubmitButtons(false);
- // Trigger an event
- this.$form.trigger($.Event(this.options.events.fieldRemoved), {
- field: field,
- element: fields
- });
- return this;
- },
- /**
- * Reset given field
- *
- * @param {String|jQuery} field The field name or field element
- * @param {Boolean} [resetValue] If true, the method resets field value to empty or remove checked/selected attribute (for radio/checkbox)
- * @returns {FormValidation.Base}
- */
- resetField: function(field, resetValue) {
- var ns = this._namespace,
- $fields = $([]);
- switch (typeof field) {
- case 'object':
- $fields = field;
- field = field.attr('data-' + ns + '-field');
- break;
- case 'string':
- $fields = this.getFieldElements(field);
- break;
- default:
- break;
- }
- var i = 0,
- total = $fields.length;
- if (this.options.fields[field]) {
- for (i = 0; i < total; i++) {
- for (var validator in this.options.fields[field].validators) {
- $fields.eq(i).removeData(ns + '.dfs.' + validator);
- }
- }
- }
- if (resetValue) {
- var type = $fields.attr('type');
- ('radio' === type || 'checkbox' === type) ? $fields.prop('checked', false).removeAttr('selected') : $fields.val('');
- }
- // Mark field as not validated yet
- this.updateStatus(field, this.STATUS_NOT_VALIDATED);
- for (i = 0; i < total; i++) {
- $fields.eq(i).trigger($.Event(this.options.events.fieldReset), {
- fv: this,
- field: field,
- element: $fields.eq(i),
- resetValue: resetValue
- });
- }
- return this;
- },
- /**
- * Reset the form
- *
- * @param {Boolean} [resetValue] If true, the method resets field value to empty or remove checked/selected attribute (for radio/checkbox)
- * @returns {FormValidation.Base}
- */
- resetForm: function(resetValue) {
- for (var field in this.options.fields) {
- this.resetField(field, resetValue);
- }
- this.$invalidFields = $([]);
- this.$submitButton = null;
- // Enable submit buttons
- this.disableSubmitButtons(false);
- this.$form.trigger($.Event(this.options.events.formReset), {
- fv: this,
- resetValue: resetValue
- });
- return this;
- },
- /**
- * Revalidate given field
- * It's used when you need to revalidate the field which its value is updated by other plugin
- *
- * @param {String|jQuery} field The field name of field element
- * @returns {FormValidation.Base}
- */
- revalidateField: function(field) {
- this.updateStatus(field, this.STATUS_NOT_VALIDATED)
- .validateField(field);
- return this;
- },
- /**
- * Set the locale
- *
- * @param {String} locale The locale in format of countrycode_LANGUAGECODE
- * @returns {FormValidation.Base}
- */
- setLocale: function(locale) {
- this.options.locale = locale;
- this.$form.trigger($.Event(this.options.events.localeChanged), {
- locale: locale,
- bv: this, // Support backward
- fv: this
- });
- return this;
- },
- /**
- * Update the option of a specific validator
- *
- * @param {String|jQuery} field The field name or field element
- * @param {String} validator The validator name
- * @param {String} option The option name
- * @param {String} value The value to set
- * @returns {FormValidation.Base}
- */
- updateOption: function(field, validator, option, value) {
- var ns = this._namespace;
- if ('object' === typeof field) {
- field = field.attr('data-' + ns + '-field');
- }
- if (this.options.fields[field] && this.options.fields[field].validators[validator]) {
- this.options.fields[field].validators[validator][option] = value;
- this.updateStatus(field, this.STATUS_NOT_VALIDATED, validator);
- }
- return this;
- },
- /**
- * Validate given container
- * It can be used with isValidContainer() when you want to work with wizard form
- *
- * @param {String|jQuery} container The container selector or element
- * @returns {FormValidation.Base}
- */
- validateContainer: function(container) {
- var that = this,
- ns = this._namespace,
- fields = [],
- $container = ('string' === typeof container) ? $(container) : container;
- if ($container.length === 0) {
- return this;
- }
- $container.find('[data-' + ns + '-field]').each(function() {
- var $field = $(this);
- if (!that._isExcluded($field)) {
- fields.push($field);
- }
- });
- var total = fields.length;
- for (var i = 0; i < total; i++) {
- this.validateField(fields[i]);
- }
- return this;
- }
- };
- // Plugin definition
- $.fn.formValidation = function(option) {
- var params = arguments;
- return this.each(function() {
- var $this = $(this),
- data = $this.data('formValidation'),
- options = 'object' === typeof option && option;
- if (!data) {
- var framework = (options.framework || $this.attr('data-fv-framework') || 'bootstrap').toLowerCase(),
- clazz = framework.substr(0, 1).toUpperCase() + framework.substr(1);
- if (typeof FormValidation.Framework[clazz] === 'undefined') {
- throw new Error('The class FormValidation.Framework.' + clazz + ' is not implemented');
- }
- data = new FormValidation.Framework[clazz](this, options);
- $this.addClass('fv-form-' + framework)
- .data('formValidation', data);
- }
- // Allow to call plugin method
- if ('string' === typeof option) {
- data[option].apply(data, Array.prototype.slice.call(params, 1));
- }
- });
- };
- $.fn.formValidation.Constructor = FormValidation.Base;
- // Default message
- $.fn.formValidation.DEFAULT_MESSAGE = 'This value is not valid';
- // The default options sorted in alphabetical order
- $.fn.formValidation.DEFAULT_OPTIONS = {
- // The first invalid field will be focused automatically
- autoFocus: true,
- // Support declarative usage (setting options via HTML 5 attributes)
- // Setting to false can improve the performance
- declarative: true,
- // The form CSS class
- elementClass: 'fv-form',
- // Use custom event name to avoid window.onerror being invoked by jQuery
- // See #630
- events: {
- // Support backward
- formInit: 'init.form.fv',
- formPreValidate: 'prevalidate.form.fv',
- formError: 'err.form.fv',
- formReset: 'rst.form.fv',
- formSuccess: 'success.form.fv',
- fieldAdded: 'added.field.fv',
- fieldRemoved: 'removed.field.fv',
- fieldInit: 'init.field.fv',
- fieldError: 'err.field.fv',
- fieldReset: 'rst.field.fv',
- fieldSuccess: 'success.field.fv',
- fieldStatus: 'status.field.fv',
- localeChanged: 'changed.locale.fv',
- validatorError: 'err.validator.fv',
- validatorSuccess: 'success.validator.fv',
- validatorIgnored: 'ignored.validator.fv'
- },
- // Indicate fields which won't be validated
- // By default, the plugin will not validate the following kind of fields:
- // - disabled
- // - hidden
- // - invisible
- //
- // The setting consists of jQuery filters. Accept 3 formats:
- // - A string. Use a comma to separate filter
- // - An array. Each element is a filter
- // - An array. Each element can be a callback function
- // function($field, validator) {
- // $field is jQuery object representing the field element
- // validator is the BootstrapValidator instance
- // return true or false;
- // }
- //
- // The 3 following settings are equivalent:
- //
- // 1) ':disabled, :hidden, :not(:visible)'
- // 2) [':disabled', ':hidden', ':not(:visible)']
- // 3) [':disabled', ':hidden', function($field) {
- // return !$field.is(':visible');
- // }]
- excluded: [':disabled', ':hidden', ':not(:visible)'],
- // Map the field name with validator rules
- fields: null,
- // Live validating option
- // Can be one of 3 values:
- // - enabled: The plugin validates fields as soon as they are changed
- // - disabled: Disable the live validating. The error messages are only shown after the form is submitted
- // - submitted: The live validating is enabled after the form is submitted
- live: 'enabled',
- // Locale in the format of languagecode_COUNTRYCODE
- locale: 'en_US',
- // Default invalid message
- message: null,
- // The field will not be live validated if its length is less than this number of characters
- threshold: null,
- // Whether to be verbose when validating a field or not.
- // Possible values:
- // - true: when a field has multiple validators, all of them will be checked, and respectively - if errors occur in
- // multiple validators, all of them will be displayed to the user
- // - false: when a field has multiple validators, validation for this field will be terminated upon the first encountered error.
- // Thus, only the very first error message related to this field will be displayed to the user
- verbose: true,
- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- // These options mostly are overridden by specific framework
- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- button: {
- // The submit buttons selector
- // These buttons will be disabled to prevent the valid form from multiple submissions
- // Don't perform validation when clicking on the submit button/input which have formnovalidate attribute
- selector: '[type="submit"]:not([formnovalidate])',
- // The disabled class
- disabled: ''
- },
- control: {
- // The CSS class for valid control
- valid: '',
- // The CSS class for invalid control
- invalid: ''
- },
- err: {
- // The CSS class of each message element
- clazz: '',
- // The error messages container. It can be:
- // - 'tooltip' if you want to use Bootstrap tooltip to show error messages
- // - 'popover' if you want to use Bootstrap popover to show error messages
- // - a CSS selector indicating the container
- // In the first two cases, since the tooltip/popover should be small enough, the plugin only shows only one error message
- // You also can define the message container for particular field
- container: null,
- // Used to determine where the messages are placed
- parent: null
- },
- // Shows ok/error/loading icons based on the field validity.
- icon: {
- valid: null,
- invalid: null,
- validating: null,
- feedback: ''
- },
- row: {
- // The CSS selector for indicating the element consists of the field
- // You should adjust this option if your form group consists of many fields which not all of them need to be validated
- selector: null,
- valid: '',
- invalid: '',
- feedback: ''
- }
- };
- }(jQuery));
- ;(function($) {
- // Helper methods, which can be used in validator class
- FormValidation.Helper = {
- /**
- * Execute a callback function
- *
- * @param {String|Function} functionName Can be
- * - name of global function
- * - name of namespace function (such as A.B.C)
- * - a function
- * @param {Array} args The callback arguments
- */
- call: function(functionName, args) {
- if ('function' === typeof functionName) {
- return functionName.apply(this, args);
- } else if ('string' === typeof functionName) {
- if ('()' === functionName.substring(functionName.length - 2)) {
- functionName = functionName.substring(0, functionName.length - 2);
- }
- var ns = functionName.split('.'),
- func = ns.pop(),
- context = window;
- for (var i = 0; i < ns.length; i++) {
- context = context[ns[i]];
- }
- return (typeof context[func] === 'undefined') ? null : context[func].apply(this, args);
- }
- },
- /**
- * Validate a date
- *
- * @param {Number} year The full year in 4 digits
- * @param {Number} month The month number
- * @param {Number} day The day number
- * @param {Boolean} [notInFuture] If true, the date must not be in the future
- * @returns {Boolean}
- */
- date: function(year, month, day, notInFuture) {
- if (isNaN(year) || isNaN(month) || isNaN(day)) {
- return false;
- }
- if (day.length > 2 || month.length > 2 || year.length > 4) {
- return false;
- }
- day = parseInt(day, 10);
- month = parseInt(month, 10);
- year = parseInt(year, 10);
- if (year < 1000 || year > 9999 || month <= 0 || month > 12) {
- return false;
- }
- var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
- // Update the number of days in Feb of leap year
- if (year % 400 === 0 || (year % 100 !== 0 && year % 4 === 0)) {
- numDays[1] = 29;
- }
- // Check the day
- if (day <= 0 || day > numDays[month - 1]) {
- return false;
- }
- if (notInFuture === true) {
- var currentDate = new Date(),
- currentYear = currentDate.getFullYear(),
- currentMonth = currentDate.getMonth(),
- currentDay = currentDate.getDate();
- return (year < currentYear
- || (year === currentYear && month - 1 < currentMonth)
- || (year === currentYear && month - 1 === currentMonth && day < currentDay));
- }
- return true;
- },
- /**
- * Format a string
- * It's used to format the error message
- * format('The field must between %s and %s', [10, 20]) = 'The field must between 10 and 20'
- *
- * @param {String} message
- * @param {Array} parameters
- * @returns {String}
- */
- format: function(message, parameters) {
- if (!$.isArray(parameters)) {
- parameters = [parameters];
- }
- for (var i in parameters) {
- message = message.replace('%s', parameters[i]);
- }
- return message;
- },
- /**
- * Implement Luhn validation algorithm
- * Credit to https://gist.github.com/ShirtlessKirk/2134376
- *
- * @see http://en.wikipedia.org/wiki/Luhn
- * @param {String} value
- * @returns {Boolean}
- */
- luhn: function(value) {
- var length = value.length,
- mul = 0,
- prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]],
- sum = 0;
- while (length--) {
- sum += prodArr[mul][parseInt(value.charAt(length), 10)];
- mul ^= 1;
- }
- return (sum % 10 === 0 && sum > 0);
- },
- /**
- * Implement modulus 11, 10 (ISO 7064) algorithm
- *
- * @param {String} value
- * @returns {Boolean}
- */
- mod11And10: function(value) {
- var check = 5,
- length = value.length;
- for (var i = 0; i < length; i++) {
- check = (((check || 10) * 2) % 11 + parseInt(value.charAt(i), 10)) % 10;
- }
- return (check === 1);
- },
- /**
- * Implements Mod 37, 36 (ISO 7064) algorithm
- * Usages:
- * mod37And36('A12425GABC1234002M')
- * mod37And36('002006673085', '0123456789')
- *
- * @param {String} value
- * @param {String} [alphabet]
- * @returns {Boolean}
- */
- mod37And36: function(value, alphabet) {
- alphabet = alphabet || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
- var modulus = alphabet.length,
- length = value.length,
- check = Math.floor(modulus / 2);
- for (var i = 0; i < length; i++) {
- check = (((check || modulus) * 2) % (modulus + 1) + alphabet.indexOf(value.charAt(i))) % modulus;
- }
- return (check === 1);
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- between: {
- 'default': 'Please enter a value between %s and %s',
- notInclusive: 'Please enter a value between %s and %s strictly'
- }
- }
- });
- FormValidation.Validator.between = {
- html5Attributes: {
- message: 'message',
- min: 'min',
- max: 'max',
- inclusive: 'inclusive'
- },
- enableByHtml5: function($field) {
- if ('range' === $field.attr('type')) {
- return {
- min: $field.attr('min'),
- max: $field.attr('max')
- };
- }
- return false;
- },
- /**
- * Return true if the input value is between (strictly or not) two given numbers
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Can consist of the following keys:
- * - min
- * - max
- *
- * The min, max keys define the number which the field value compares to. min, max can be
- * - A number
- * - Name of field which its value defines the number
- * - Name of callback function that returns the number
- * - A callback function that returns the number
- *
- * - inclusive [optional]: Can be true or false. Default is true
- * - message: The invalid message
- * @returns {Boolean|Object}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName);
- if (value === '') {
- return true;
- }
- value = this._format(value);
- var locale = validator.getLocale(),
- min = $.isNumeric(options.min) ? options.min : validator.getDynamicOption($field, options.min),
- max = $.isNumeric(options.max) ? options.max : validator.getDynamicOption($field, options.max),
- minValue = this._format(min),
- maxValue = this._format(max);
- return (options.inclusive === true || options.inclusive === undefined)
- ? {
- valid: $.isNumeric(value) && parseFloat(value) >= minValue && parseFloat(value) <= maxValue,
- message: FormValidation.Helper.format(options.message || FormValidation.I18n[locale].between['default'], [min, max])
- }
- : {
- valid: $.isNumeric(value) && parseFloat(value) > minValue && parseFloat(value) < maxValue,
- message: FormValidation.Helper.format(options.message || FormValidation.I18n[locale].between.notInclusive, [min, max])
- };
- },
- _format: function(value) {
- return (value + '').replace(',', '.');
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- callback: {
- 'default': 'Please enter a valid value'
- }
- }
- });
- FormValidation.Validator.callback = {
- priority: 999,
- html5Attributes: {
- message: 'message',
- callback: 'callback'
- },
- /**
- * Return result from the callback method
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Can consist of the following keys:
- * - callback: The callback method that passes parameters:
- * callback: function(fieldValue, validator, $field) {
- * // fieldValue is the value of field
- * // validator is instance of FormValidation.Base
- * // $field is the field element
- * }
- * - message: The invalid message
- * @returns {Deferred}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName),
- dfd = new $.Deferred(),
- result = { valid: true };
- if (options.callback) {
- var response = FormValidation.Helper.call(options.callback, [value, validator, $field]);
- result = ('boolean' === typeof response || null === response) ? { valid: response } : response;
- }
- dfd.resolve($field, validatorName, result);
- return dfd;
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- choice: {
- 'default': 'Please enter a valid value',
- less: 'Please choose %s options at minimum',
- more: 'Please choose %s options at maximum',
- between: 'Please choose %s - %s options'
- }
- }
- });
- FormValidation.Validator.choice = {
- html5Attributes: {
- message: 'message',
- min: 'min',
- max: 'max'
- },
- /**
- * Check if the number of checked boxes are less or more than a given number
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Consists of following keys:
- * - min
- * - max
- *
- * At least one of two keys is required
- * The min, max keys define the number which the field value compares to. min, max can be
- * - A number
- * - Name of field which its value defines the number
- * - Name of callback function that returns the number
- * - A callback function that returns the number
- *
- * - message: The invalid message
- * @returns {Object}
- */
- validate: function(validator, $field, options, validatorName) {
- var locale = validator.getLocale(),
- ns = validator.getNamespace(),
- numChoices = $field.is('select')
- ? validator.getFieldElements($field.attr('data-' + ns + '-field')).find('option').filter(':selected').length
- : validator.getFieldElements($field.attr('data-' + ns + '-field')).filter(':checked').length,
- min = options.min ? ($.isNumeric(options.min) ? options.min : validator.getDynamicOption($field, options.min)) : null,
- max = options.max ? ($.isNumeric(options.max) ? options.max : validator.getDynamicOption($field, options.max)) : null,
- isValid = true,
- message = options.message || FormValidation.I18n[locale].choice['default'];
- if ((min && numChoices < parseInt(min, 10)) || (max && numChoices > parseInt(max, 10))) {
- isValid = false;
- }
- switch (true) {
- case (!!min && !!max):
- message = FormValidation.Helper.format(options.message || FormValidation.I18n[locale].choice.between, [parseInt(min, 10), parseInt(max, 10)]);
- break;
- case (!!min):
- message = FormValidation.Helper.format(options.message || FormValidation.I18n[locale].choice.less, parseInt(min, 10));
- break;
- case (!!max):
- message = FormValidation.Helper.format(options.message || FormValidation.I18n[locale].choice.more, parseInt(max, 10));
- break;
- default:
- break;
- }
- return { valid: isValid, message: message };
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- color: {
- 'default': 'Please enter a valid color'
- }
- }
- });
- FormValidation.Validator.color = {
- html5Attributes: {
- message: 'message',
- type: 'type'
- },
- enableByHtml5: function($field) {
- return ('color' === $field.attr('type'));
- },
- SUPPORTED_TYPES: [
- 'hex', 'rgb', 'rgba', 'hsl', 'hsla', 'keyword'
- ],
- KEYWORD_COLORS: [
- // Colors start with A
- 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure',
- // B
- 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood',
- // C
- 'cadetblue', 'chartreuse', 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan',
- // D
- 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgreen', 'darkgrey', 'darkkhaki', 'darkmagenta',
- 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue',
- 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray',
- 'dimgrey', 'dodgerblue',
- // F
- 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia',
- // G
- 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'grey',
- // H
- 'honeydew', 'hotpink',
- // I
- 'indianred', 'indigo', 'ivory',
- // K
- 'khaki',
- // L
- 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 'lightcyan',
- 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightgrey', 'lightpink', 'lightsalmon', 'lightseagreen',
- 'lightskyblue', 'lightslategray', 'lightslategrey', 'lightsteelblue', 'lightyellow', 'lime', 'limegreen',
- 'linen',
- // M
- 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen',
- 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream',
- 'mistyrose', 'moccasin',
- // N
- 'navajowhite', 'navy',
- // O
- 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid',
- // P
- 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink',
- 'plum', 'powderblue', 'purple',
- // R
- 'red', 'rosybrown', 'royalblue',
- // S
- 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue',
- 'slategray', 'slategrey', 'snow', 'springgreen', 'steelblue',
- // T
- 'tan', 'teal', 'thistle', 'tomato', 'transparent', 'turquoise',
- // V
- 'violet',
- // W
- 'wheat', 'white', 'whitesmoke',
- // Y
- 'yellow', 'yellowgreen'
- ],
- /**
- * Return true if the input value is a valid color
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Can consist of the following keys:
- * - message: The invalid message
- * - type: The array of valid color types
- * @returns {Boolean}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName);
- if (value === '') {
- return true;
- }
- // Only accept 6 hex character values due to the HTML 5 spec
- // See http://www.w3.org/TR/html-markup/input.color.html#input.color.attrs.value
- if (this.enableByHtml5($field)) {
- return /^#[0-9A-F]{6}$/i.test(value);
- }
- var types = options.type || this.SUPPORTED_TYPES;
- if (!$.isArray(types)) {
- types = types.replace(/s/g, '').split(',');
- }
- var method,
- type,
- isValid = false;
- for (var i = 0; i < types.length; i++) {
- type = types[i];
- method = '_' + type.toLowerCase();
- isValid = isValid || this[method](value);
- if (isValid) {
- return true;
- }
- }
- return false;
- },
- _hex: function(value) {
- return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value);
- },
- _hsl: function(value) {
- return /^hsl\((\s*(-?\d+)\s*,)(\s*(\b(0?\d{1,2}|100)\b%)\s*,)(\s*(\b(0?\d{1,2}|100)\b%)\s*)\)$/.test(value);
- },
- _hsla: function(value) {
- return /^hsla\((\s*(-?\d+)\s*,)(\s*(\b(0?\d{1,2}|100)\b%)\s*,){2}(\s*(0?(\.\d+)?|1(\.0+)?)\s*)\)$/.test(value);
- },
- _keyword: function(value) {
- return $.inArray(value, this.KEYWORD_COLORS) >= 0;
- },
- _rgb: function(value) {
- var regexInteger = /^rgb\((\s*(\b([01]?\d{1,2}|2[0-4]\d|25[0-5])\b)\s*,){2}(\s*(\b([01]?\d{1,2}|2[0-4]\d|25[0-5])\b)\s*)\)$/,
- regexPercent = /^rgb\((\s*(\b(0?\d{1,2}|100)\b%)\s*,){2}(\s*(\b(0?\d{1,2}|100)\b%)\s*)\)$/;
- return regexInteger.test(value) || regexPercent.test(value);
- },
- _rgba: function(value) {
- var regexInteger = /^rgba\((\s*(\b([01]?\d{1,2}|2[0-4]\d|25[0-5])\b)\s*,){3}(\s*(0?(\.\d+)?|1(\.0+)?)\s*)\)$/,
- regexPercent = /^rgba\((\s*(\b(0?\d{1,2}|100)\b%)\s*,){3}(\s*(0?(\.\d+)?|1(\.0+)?)\s*)\)$/;
- return regexInteger.test(value) || regexPercent.test(value);
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- creditCard: {
- 'default': 'Please enter a valid credit card number'
- }
- }
- });
- FormValidation.Validator.creditCard = {
- /**
- * Return true if the input value is valid credit card number
- * Based on https://gist.github.com/DiegoSalazar/4075533
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} [options] Can consist of the following key:
- * - message: The invalid message
- * @returns {Boolean|Object}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName);
- if (value === '') {
- return true;
- }
- // Accept only digits, dashes or spaces
- if (/[^0-9-\s]+/.test(value)) {
- return false;
- }
- value = value.replace(/\D/g, '');
- if (!FormValidation.Helper.luhn(value)) {
- return false;
- }
- // Validate the card number based on prefix (IIN ranges) and length
- var cards = {
- AMERICAN_EXPRESS: {
- length: [15],
- prefix: ['34', '37']
- },
- DANKORT: {
- length: [16],
- prefix: ['5019']
- },
- DINERS_CLUB: {
- length: [14],
- prefix: ['300', '301', '302', '303', '304', '305', '36']
- },
- DINERS_CLUB_US: {
- length: [16],
- prefix: ['54', '55']
- },
- DISCOVER: {
- length: [16],
- prefix: ['6011', '622126', '622127', '622128', '622129', '62213',
- '62214', '62215', '62216', '62217', '62218', '62219',
- '6222', '6223', '6224', '6225', '6226', '6227', '6228',
- '62290', '62291', '622920', '622921', '622922', '622923',
- '622924', '622925', '644', '645', '646', '647', '648',
- '649', '65']
- },
- ELO: {
- length: [16],
- prefix: ['4011', '4312', '4389', '4514', '4573', '4576',
- '5041', '5066', '5067', '509',
- '6277', '6362', '6363', '650', '6516', '6550']
- },
- FORBRUGSFORENINGEN: {
- length: [16],
- prefix: ['600722']
- },
- JCB: {
- length: [16],
- prefix: ['3528', '3529', '353', '354', '355', '356', '357', '358']
- },
- LASER: {
- length: [16, 17, 18, 19],
- prefix: ['6304', '6706', '6771', '6709']
- },
- MAESTRO: {
- length: [12, 13, 14, 15, 16, 17, 18, 19],
- prefix: ['5018', '5020', '5038', '5868', '6304', '6759', '6761', '6762', '6763', '6764', '6765', '6766']
- },
- MASTERCARD: {
- length: [16],
- prefix: ['51', '52', '53', '54', '55']
- },
- SOLO: {
- length: [16, 18, 19],
- prefix: ['6334', '6767']
- },
- UNIONPAY: {
- length: [16, 17, 18, 19],
- prefix: ['622126', '622127', '622128', '622129', '62213', '62214',
- '62215', '62216', '62217', '62218', '62219', '6222', '6223',
- '6224', '6225', '6226', '6227', '6228', '62290', '62291',
- '622920', '622921', '622922', '622923', '622924', '622925']
- },
- VISA_ELECTRON: {
- length: [16],
- prefix: ['4026', '417500', '4405', '4508', '4844', '4913', '4917']
- },
- VISA: {
- length: [16],
- prefix: ['4']
- }
- };
- var type, i;
- for (type in cards) {
- for (i in cards[type].prefix) {
- if (value.substr(0, cards[type].prefix[i].length) === cards[type].prefix[i] // Check the prefix
- && $.inArray(value.length, cards[type].length) !== -1) // and length
- {
- return {
- valid: true,
- type: type
- };
- }
- }
- }
- return false;
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- date: {
- 'default': 'Please enter a valid date',
- min: 'Please enter a date after %s',
- max: 'Please enter a date before %s',
- range: 'Please enter a date in the range %s - %s'
- }
- }
- });
- FormValidation.Validator.date = {
- html5Attributes: {
- message: 'message',
- format: 'format',
- min: 'min',
- max: 'max',
- separator: 'separator'
- },
- /**
- * Return true if the input value is valid date
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Can consist of the following keys:
- * - message: The invalid message
- * - min: the minimum date
- * - max: the maximum date
- * - separator: Use to separate the date, month, and year.
- * By default, it is /
- * - format: The date format. Default is MM/DD/YYYY
- * The format can be:
- *
- * i) date: Consist of DD, MM, YYYY parts which are separated by the separator option
- * ii) date and time:
- * The time can consist of h, m, s parts which are separated by :
- * ii) date, time and A (indicating AM or PM)
- * @returns {Boolean|Object}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName);
- if (value === '') {
- return true;
- }
- options.format = options.format || 'MM/DD/YYYY';
- // #683: Force the format to YYYY-MM-DD as the default browser behaviour when using type="date" attribute
- if ($field.attr('type') === 'date') {
- options.format = 'YYYY-MM-DD';
- }
- var locale = validator.getLocale(),
- message = options.message || FormValidation.I18n[locale].date['default'],
- formats = options.format.split(' '),
- dateFormat = formats[0],
- timeFormat = (formats.length > 1) ? formats[1] : null,
- amOrPm = (formats.length > 2) ? formats[2] : null,
- sections = value.split(' '),
- date = sections[0],
- time = (sections.length > 1) ? sections[1] : null;
- if (formats.length !== sections.length) {
- return {
- valid: false,
- message: message
- };
- }
- // Determine the separator
- var separator = options.separator;
- if (!separator) {
- separator = (date.indexOf('/') !== -1)
- ? '/'
- : ((date.indexOf('-') !== -1) ? '-' : ((date.indexOf('.') !== -1) ? '.' : null));
- }
- if (separator === null || date.indexOf(separator) === -1) {
- return {
- valid: false,
- message: message
- };
- }
- // Determine the date
- date = date.split(separator);
- dateFormat = dateFormat.split(separator);
- if (date.length !== dateFormat.length) {
- return {
- valid: false,
- message: message
- };
- }
- var year = date[$.inArray('YYYY', dateFormat)],
- month = date[$.inArray('MM', dateFormat)],
- day = date[$.inArray('DD', dateFormat)];
- if (!year || !month || !day || year.length !== 4) {
- return {
- valid: false,
- message: message
- };
- }
- // Determine the time
- var minutes = null, hours = null, seconds = null;
- if (timeFormat) {
- timeFormat = timeFormat.split(':');
- time = time.split(':');
- if (timeFormat.length !== time.length) {
- return {
- valid: false,
- message: message
- };
- }
- hours = time.length > 0 ? time[0] : null;
- minutes = time.length > 1 ? time[1] : null;
- seconds = time.length > 2 ? time[2] : null;
- if (hours === '' || minutes === '' || seconds === '') {
- return {
- valid: false,
- message: message
- };
- }
- // Validate seconds
- if (seconds) {
- if (isNaN(seconds) || seconds.length > 2) {
- return {
- valid: false,
- message: message
- };
- }
- seconds = parseInt(seconds, 10);
- if (seconds < 0 || seconds > 60) {
- return {
- valid: false,
- message: message
- };
- }
- }
- // Validate hours
- if (hours) {
- if (isNaN(hours) || hours.length > 2) {
- return {
- valid: false,
- message: message
- };
- }
- hours = parseInt(hours, 10);
- if (hours < 0 || hours >= 24 || (amOrPm && hours > 12)) {
- return {
- valid: false,
- message: message
- };
- }
- }
- // Validate minutes
- if (minutes) {
- if (isNaN(minutes) || minutes.length > 2) {
- return {
- valid: false,
- message: message
- };
- }
- minutes = parseInt(minutes, 10);
- if (minutes < 0 || minutes > 59) {
- return {
- valid: false,
- message: message
- };
- }
- }
- }
- // Validate day, month, and year
- var valid = FormValidation.Helper.date(year, month, day),
- min = null,
- max = null,
- minOption = options.min,
- maxOption = options.max;
- if (minOption) {
- min = (minOption instanceof Date)
- ? minOption
- : (this._parseDate(minOption, dateFormat, separator) ||
- this._parseDate(validator.getDynamicOption($field, minOption), dateFormat, separator));
- // In order to avoid displaying a date string like "Mon Dec 08 2014 19:14:12 GMT+0000 (WET)"
- minOption = this._formatDate(min, options.format);
- }
- if (maxOption) {
- max = (maxOption instanceof Date)
- ? maxOption
- : (this._parseDate(maxOption, dateFormat, separator) ||
- this._parseDate(validator.getDynamicOption($field, maxOption), dateFormat, separator));
- // In order to avoid displaying a date string like "Mon Dec 08 2014 19:14:12 GMT+0000 (WET)"
- maxOption = this._formatDate(max, options.format);
- }
- date = new Date(year, month -1, day, hours, minutes, seconds);
- switch (true) {
- case (minOption && !maxOption && valid):
- valid = date.getTime() >= min.getTime();
- message = options.message || FormValidation.Helper.format(FormValidation.I18n[locale].date.min, minOption);
- break;
- case (maxOption && !minOption && valid):
- valid = date.getTime() <= max.getTime();
- message = options.message || FormValidation.Helper.format(FormValidation.I18n[locale].date.max, maxOption);
- break;
- case (maxOption && minOption && valid):
- valid = date.getTime() <= max.getTime() && date.getTime() >= min.getTime();
- message = options.message || FormValidation.Helper.format(FormValidation.I18n[locale].date.range, [minOption, maxOption]);
- break;
- default:
- break;
- }
- return {
- valid: valid,
- date: date,
- message: message
- };
- },
- /**
- * Return a date object after parsing the date string
- *
- * @param {Date|String} date The date string to parse
- * @param {String} format The date format
- * The format can be:
- * - date: Consist of DD, MM, YYYY parts which are separated by the separator option
- * - date and time:
- * The time can consist of h, m, s parts which are separated by :
- * @param {String} separator The separator used to separate the date, month, and year
- * @returns {Date}
- */
- _parseDate: function(date, format, separator) {
- if (date instanceof Date) {
- return date;
- }
- if (typeof date !== 'string') {
- return null;
- }
- // Ensure that the format must consist of year, month and day patterns
- var yearIndex = $.inArray('YYYY', format),
- monthIndex = $.inArray('MM', format),
- dayIndex = $.inArray('DD', format);
- if (yearIndex === -1 || monthIndex === -1 || dayIndex === -1) {
- return null;
- }
- var minutes = 0, hours = 0, seconds = 0,
- sections = date.split(' '),
- dateSection = sections[0].split(separator);
- if (dateSection.length < 3) {
- return null;
- }
- if (sections.length > 1) {
- var timeSection = sections[1].split(':');
- hours = timeSection.length > 0 ? timeSection[0] : null;
- minutes = timeSection.length > 1 ? timeSection[1] : null;
- seconds = timeSection.length > 2 ? timeSection[2] : null;
- }
- return new Date(dateSection[yearIndex], dateSection[monthIndex] - 1, dateSection[dayIndex],
- hours, minutes, seconds);
- },
- /**
- * Format date
- *
- * @param {Date} date The date object to format
- * @param {String} format The date format
- * The format can consist of the following tokens:
- * d Day of the month without leading zeros (1 through 31)
- * dd Day of the month with leading zeros (01 through 31)
- * m Month without leading zeros (1 through 12)
- * mm Month with leading zeros (01 through 12)
- * yy Last two digits of year (for example: 14)
- * yyyy Full four digits of year (for example: 2014)
- * h Hours without leading zeros (1 through 12)
- * hh Hours with leading zeros (01 through 12)
- * H Hours without leading zeros (0 through 23)
- * HH Hours with leading zeros (00 through 23)
- * M Minutes without leading zeros (0 through 59)
- * MM Minutes with leading zeros (00 through 59)
- * s Seconds without leading zeros (0 through 59)
- * ss Seconds with leading zeros (00 through 59)
- * @returns {String}
- */
- _formatDate: function(date, format) {
- format = format
- .replace(/Y/g, 'y')
- .replace(/M/g, 'm')
- .replace(/D/g, 'd')
- .replace(/:m/g, ':M')
- .replace(/:mm/g, ':MM')
- .replace(/:S/, ':s')
- .replace(/:SS/, ':ss');
- var replacer = {
- d: function(date) {
- return date.getDate();
- },
- dd: function(date) {
- var d = date.getDate();
- return (d < 10) ? '0' + d : d;
- },
- m: function(date) {
- return date.getMonth() + 1;
- },
- mm: function(date) {
- var m = date.getMonth() + 1;
- return m < 10 ? '0' + m : m;
- },
- yy: function(date) {
- return ('' + date.getFullYear()).substr(2);
- },
- yyyy: function(date) {
- return date.getFullYear();
- },
- h: function(date) {
- return date.getHours() % 12 || 12;
- },
- hh: function(date) {
- var h = date.getHours() % 12 || 12;
- return h < 10 ? '0' + h : h;
- },
- H: function(date) {
- return date.getHours();
- },
- HH: function(date) {
- var H = date.getHours();
- return H < 10 ? '0' + H : H;
- },
- M: function(date) {
- return date.getMinutes();
- },
- MM: function(date) {
- var M = date.getMinutes();
- return M < 10 ? '0' + M : M;
- },
- s: function(date) {
- return date.getSeconds();
- },
- ss: function(date) {
- var s = date.getSeconds();
- return s < 10 ? '0' + s : s;
- }
- };
- return format.replace(/d{1,4}|m{1,4}|yy(?:yy)?|([HhMs])\1?|"[^"]*"|'[^']*'/g, function(match) {
- return replacer[match] ? replacer[match](date) : match.slice(1, match.length - 1);
- });
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- different: {
- 'default': 'Please enter a different value'
- }
- }
- });
- FormValidation.Validator.different = {
- html5Attributes: {
- message: 'message',
- field: 'field'
- },
- /**
- * Bind the validator on the live change of the field to compare with current one
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Consists of the following key:
- * - field: The name of field that will be used to compare with current one
- */
- init: function(validator, $field, options, validatorName) {
- var fields = options.field.split(',');
- for (var i = 0; i < fields.length; i++) {
- var compareWith = validator.getFieldElements($.trim(fields[i]));
- validator.onLiveChange(compareWith, 'live_' + validatorName, function() {
- var status = validator.getStatus($field, validatorName);
- if (status !== validator.STATUS_NOT_VALIDATED) {
- validator.revalidateField($field);
- }
- });
- }
- },
- /**
- * Unbind the validator on the live change of the field to compare with current one
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Consists of the following key:
- * - field: The name of field that will be used to compare with current one
- */
- destroy: function(validator, $field, options, validatorName) {
- var fields = options.field.split(',');
- for (var i = 0; i < fields.length; i++) {
- var compareWith = validator.getFieldElements($.trim(fields[i]));
- validator.offLiveChange(compareWith, 'live_' + validatorName);
- }
- },
- /**
- * Return true if the input value is different with given field's value
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Consists of the following key:
- * - field: The name of field that will be used to compare with current one
- * - message: The invalid message
- * @returns {Boolean}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName);
- if (value === '') {
- return true;
- }
- var fields = options.field.split(','),
- isValid = true;
- for (var i = 0; i < fields.length; i++) {
- var compareWith = validator.getFieldElements($.trim(fields[i]));
- if (compareWith == null || compareWith.length === 0) {
- continue;
- }
- var compareValue = validator.getFieldValue(compareWith, validatorName);
- if (value === compareValue) {
- isValid = false;
- } else if (compareValue !== '') {
- validator.updateStatus(compareWith, validator.STATUS_VALID, validatorName);
- }
- }
- return isValid;
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- digits: {
- 'default': 'Please enter only digits'
- }
- }
- });
- FormValidation.Validator.digits = {
- /**
- * Return true if the input value contains digits only
- *
- * @param {FormValidation.Base} validator Validate plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} [options]
- * @returns {Boolean}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName);
- if (value === '') {
- return true;
- }
- return /^\d+$/.test(value);
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- emailAddress: {
- 'default': 'Please enter a valid email address'
- }
- }
- });
- FormValidation.Validator.emailAddress = {
- html5Attributes: {
- message: 'message',
- multiple: 'multiple',
- separator: 'separator'
- },
- enableByHtml5: function($field) {
- return ('email' === $field.attr('type'));
- },
- /**
- * Return true if and only if the input value is a valid email address
- *
- * @param {FormValidation.Base} validator Validate plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} [options]
- * - multiple: Allow multiple email addresses, separated by a comma or semicolon; default is false.
- * - separator: Regex for character or characters expected as separator between addresses; default is comma /[,;]/, i.e. comma or semicolon.
- * @returns {Boolean}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName);
- if (value === '') {
- return true;
- }
- // Email address regular expression
- // http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
- var emailRegExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
- allowMultiple = options.multiple === true || options.multiple === 'true';
- if (allowMultiple) {
- var separator = options.separator || /[,;]/,
- addresses = this._splitEmailAddresses(value, separator);
- for (var i = 0; i < addresses.length; i++) {
- if (!emailRegExp.test(addresses[i])) {
- return false;
- }
- }
- return true;
- } else {
- return emailRegExp.test(value);
- }
- },
- _splitEmailAddresses: function(emailAddresses, separator) {
- var quotedFragments = emailAddresses.split(/"/),
- quotedFragmentCount = quotedFragments.length,
- emailAddressArray = [],
- nextEmailAddress = '';
- for (var i = 0; i < quotedFragmentCount; i++) {
- if (i % 2 === 0) {
- var splitEmailAddressFragments = quotedFragments[i].split(separator),
- splitEmailAddressFragmentCount = splitEmailAddressFragments.length;
- if (splitEmailAddressFragmentCount === 1) {
- nextEmailAddress += splitEmailAddressFragments[0];
- } else {
- emailAddressArray.push(nextEmailAddress + splitEmailAddressFragments[0]);
- for (var j = 1; j < splitEmailAddressFragmentCount - 1; j++) {
- emailAddressArray.push(splitEmailAddressFragments[j]);
- }
- nextEmailAddress = splitEmailAddressFragments[splitEmailAddressFragmentCount - 1];
- }
- } else {
- nextEmailAddress += '"' + quotedFragments[i];
- if (i < quotedFragmentCount - 1) {
- nextEmailAddress += '"';
- }
- }
- }
- emailAddressArray.push(nextEmailAddress);
- return emailAddressArray;
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- file: {
- 'default': 'Please choose a valid file'
- }
- }
- });
- FormValidation.Validator.file = {
- Error: {
- EXTENSION: 'EXTENSION',
- MAX_FILES: 'MAX_FILES',
- MAX_SIZE: 'MAX_SIZE',
- MAX_TOTAL_SIZE: 'MAX_TOTAL_SIZE',
- MIN_FILES: 'MIN_FILES',
- MIN_SIZE: 'MIN_SIZE',
- MIN_TOTAL_SIZE: 'MIN_TOTAL_SIZE',
- TYPE: 'TYPE'
- },
- html5Attributes: {
- extension: 'extension',
- maxfiles: 'maxFiles',
- minfiles: 'minFiles',
- maxsize: 'maxSize',
- minsize: 'minSize',
- maxtotalsize: 'maxTotalSize',
- mintotalsize: 'minTotalSize',
- message: 'message',
- type: 'type'
- },
- /**
- * Validate upload file. Use HTML 5 API if the browser supports
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Can consist of the following keys:
- * - extension: The allowed extensions, separated by a comma
- * - maxFiles: The maximum number of files
- * - minFiles: The minimum number of files
- * - maxSize: The maximum size in bytes
- * - minSize: The minimum size in bytes
- * - maxTotalSize: The maximum size in bytes for all files
- * - minTotalSize: The minimum size in bytes for all files
- * - message: The invalid message
- * - type: The allowed MIME type, separated by a comma
- * @returns {Boolean|Object}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName);
- if (value === '') {
- return true;
- }
- var ext,
- extensions = options.extension ? options.extension.toLowerCase().split(',') : null,
- types = options.type ? options.type.toLowerCase().split(',') : null,
- html5 = (window.File && window.FileList && window.FileReader);
- if (html5) {
- // Get FileList instance
- var files = $field.get(0).files,
- total = files.length,
- totalSize = 0;
- // Check the maxFiles
- if (options.maxFiles && total > parseInt(options.maxFiles, 10)) {
- return {
- valid: false,
- error: this.Error.MAX_FILES
- };
- }
- // Check the minFiles
- if (options.minFiles && total < parseInt(options.minFiles, 10)) {
- return {
- valid: false,
- error: this.Error.MIN_FILES
- };
- }
- var metaData = {};
- for (var i = 0; i < total; i++) {
- totalSize += files[i].size;
- ext = files[i].name.substr(files[i].name.lastIndexOf('.') + 1);
- metaData = {
- file: files[i],
- size: files[i].size,
- ext: ext,
- type: files[i].type
- };
- // Check the minSize
- if (options.minSize && files[i].size < parseInt(options.minSize, 10)) {
- return {
- valid: false,
- error: this.Error.MIN_SIZE,
- metaData: metaData
- };
- }
- // Check the maxSize
- if (options.maxSize && files[i].size > parseInt(options.maxSize, 10)) {
- return {
- valid: false,
- error: this.Error.MAX_SIZE,
- metaData: metaData
- };
- }
- // Check file extension
- if (extensions && $.inArray(ext.toLowerCase(), extensions) === -1) {
- return {
- valid: false,
- error: this.Error.EXTENSION,
- metaData: metaData
- };
- }
- // Check file type
- if (files[i].type && types && $.inArray(files[i].type.toLowerCase(), types) === -1) {
- return {
- valid: false,
- error: this.Error.TYPE,
- metaData: metaData
- };
- }
- }
- // Check the maxTotalSize
- if (options.maxTotalSize && totalSize > parseInt(options.maxTotalSize, 10)) {
- return {
- valid: false,
- error: this.Error.MAX_TOTAL_SIZE,
- metaData: {
- totalSize: totalSize
- }
- };
- }
- // Check the minTotalSize
- if (options.minTotalSize && totalSize < parseInt(options.minTotalSize, 10)) {
- return {
- valid: false,
- error: this.Error.MIN_TOTAL_SIZE,
- metaData: {
- totalSize: totalSize
- }
- };
- }
- } else {
- // Check file extension
- ext = value.substr(value.lastIndexOf('.') + 1);
- if (extensions && $.inArray(ext.toLowerCase(), extensions) === -1) {
- return {
- valid: false,
- error: this.Error.EXTENSION,
- metaData: {
- ext: ext
- }
- };
- }
- }
- return true;
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- greaterThan: {
- 'default': 'Please enter a value greater than or equal to %s',
- notInclusive: 'Please enter a value greater than %s'
- }
- }
- });
- FormValidation.Validator.greaterThan = {
- html5Attributes: {
- message: 'message',
- value: 'value',
- inclusive: 'inclusive'
- },
- enableByHtml5: function($field) {
- var type = $field.attr('type'),
- min = $field.attr('min');
- if (min && type !== 'date') {
- return {
- value: min
- };
- }
- return false;
- },
- /**
- * Return true if the input value is greater than or equals to given number
- *
- * @param {FormValidation.Base} validator Validate plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Can consist of the following keys:
- * - value: Define the number to compare with. It can be
- * - A number
- * - Name of field which its value defines the number
- * - Name of callback function that returns the number
- * - A callback function that returns the number
- *
- * - inclusive [optional]: Can be true or false. Default is true
- * - message: The invalid message
- * @returns {Boolean|Object}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName);
- if (value === '') {
- return true;
- }
-
- value = this._format(value);
- var locale = validator.getLocale(),
- compareTo = $.isNumeric(options.value) ? options.value : validator.getDynamicOption($field, options.value),
- compareToValue = this._format(compareTo);
- return (options.inclusive === true || options.inclusive === undefined)
- ? {
- valid: $.isNumeric(value) && parseFloat(value) >= compareToValue,
- message: FormValidation.Helper.format(options.message || FormValidation.I18n[locale].greaterThan['default'], compareTo)
- }
- : {
- valid: $.isNumeric(value) && parseFloat(value) > compareToValue,
- message: FormValidation.Helper.format(options.message || FormValidation.I18n[locale].greaterThan.notInclusive, compareTo)
- };
- },
- _format: function(value) {
- return (value + '').replace(',', '.');
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- identical: {
- 'default': 'Please enter the same value'
- }
- }
- });
- FormValidation.Validator.identical = {
- html5Attributes: {
- message: 'message',
- field: 'field'
- },
- /**
- * Bind the validator on the live change of the field to compare with current one
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Consists of the following key:
- * - field: The name of field that will be used to compare with current one
- */
- init: function(validator, $field, options, validatorName) {
- var compareWith = validator.getFieldElements(options.field);
- validator.onLiveChange(compareWith, 'live_' + validatorName, function() {
- var status = validator.getStatus($field, validatorName);
- if (status !== validator.STATUS_NOT_VALIDATED) {
- validator.revalidateField($field);
- }
- });
- },
- /**
- * Unbind the validator on the live change of the field to compare with current one
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Consists of the following key:
- * - field: The name of field that will be used to compare with current one
- */
- destroy: function(validator, $field, options, validatorName) {
- var compareWith = validator.getFieldElements(options.field);
- validator.offLiveChange(compareWith, 'live_' + validatorName);
- },
- /**
- * Check if input value equals to value of particular one
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Consists of the following key:
- * - field: The name of field that will be used to compare with current one
- * @returns {Boolean}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName),
- compareWith = validator.getFieldElements(options.field);
- if (compareWith === null || compareWith.length === 0) {
- return true;
- }
- var compareValue = validator.getFieldValue(compareWith, validatorName);
- if (value === compareValue) {
- validator.updateStatus(compareWith, validator.STATUS_VALID, validatorName);
- return true;
- }
- return false;
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- integer: {
- 'default': 'Please enter a valid number'
- }
- }
- });
- FormValidation.Validator.integer = {
- html5Attributes: {
- message: 'message',
- thousandsseparator: 'thousandsSeparator',
- decimalseparator: 'decimalSeparator'
- },
- enableByHtml5: function($field) {
- return ('number' === $field.attr('type')) && ($field.attr('step') === undefined || $field.attr('step') % 1 === 0);
- },
- /**
- * Return true if the input value is an integer
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Can consist of the following key:
- * - message: The invalid message
- * - thousandsSeparator: The thousands separator. It's empty by default
- * - decimalSeparator: The decimal separator. It's '.' by default
- * @returns {Boolean}
- */
- validate: function(validator, $field, options, validatorName) {
- if (this.enableByHtml5($field) && $field.get(0).validity && $field.get(0).validity.badInput === true) {
- return false;
- }
- var value = validator.getFieldValue($field, validatorName);
- if (value === '') {
- return true;
- }
- var decimalSeparator = options.decimalSeparator || '.',
- thousandsSeparator = options.thousandsSeparator || '';
- decimalSeparator = (decimalSeparator === '.') ? '\\.' : decimalSeparator;
- thousandsSeparator = (thousandsSeparator === '.') ? '\\.' : thousandsSeparator;
- var testRegexp = new RegExp('^-?[0-9]{1,3}(' + thousandsSeparator + '[0-9]{3})*(' + decimalSeparator + '[0-9]+)?$'),
- thousandsReplacer = new RegExp(thousandsSeparator, 'g');
- if (!testRegexp.test(value)) {
- return false;
- }
- // Replace thousands separator with blank
- if (thousandsSeparator) {
- value = value.replace(thousandsReplacer, '');
- }
- // Replace decimal separator with a dot
- if (decimalSeparator) {
- value = value.replace(decimalSeparator, '.');
- }
- if (isNaN(value) || !isFinite(value)) {
- return false;
- }
- // TODO: Use Number.isInteger() if available
- value = parseFloat(value);
- return Math.floor(value) === value;
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- lessThan: {
- 'default': 'Please enter a value less than or equal to %s',
- notInclusive: 'Please enter a value less than %s'
- }
- }
- });
- FormValidation.Validator.lessThan = {
- html5Attributes: {
- message: 'message',
- value: 'value',
- inclusive: 'inclusive'
- },
- enableByHtml5: function($field) {
- var type = $field.attr('type'),
- max = $field.attr('max');
- if (max && type !== 'date') {
- return {
- value: max
- };
- }
- return false;
- },
- /**
- * Return true if the input value is less than or equal to given number
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Can consist of the following keys:
- * - value: The number used to compare to. It can be
- * - A number
- * - Name of field which its value defines the number
- * - Name of callback function that returns the number
- * - A callback function that returns the number
- *
- * - inclusive [optional]: Can be true or false. Default is true
- * - message: The invalid message
- * @returns {Boolean|Object}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName);
- if (value === '') {
- return true;
- }
-
- value = this._format(value);
- var locale = validator.getLocale(),
- compareTo = $.isNumeric(options.value) ? options.value : validator.getDynamicOption($field, options.value),
- compareToValue = this._format(compareTo);
- return (options.inclusive === true || options.inclusive === undefined)
- ? {
- valid: $.isNumeric(value) && parseFloat(value) <= compareToValue,
- message: FormValidation.Helper.format(options.message || FormValidation.I18n[locale].lessThan['default'], compareTo)
- }
- : {
- valid: $.isNumeric(value) && parseFloat(value) < compareToValue,
- message: FormValidation.Helper.format(options.message || FormValidation.I18n[locale].lessThan.notInclusive, compareTo)
- };
- },
- _format: function(value) {
- return (value + '').replace(',', '.');
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- notEmpty: {
- 'default': 'Please enter a value'
- }
- }
- });
- FormValidation.Validator.notEmpty = {
- enableByHtml5: function($field) {
- var required = $field.attr('required') + '';
- return ('required' === required || 'true' === required);
- },
- /**
- * Check if input value is empty or not
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options
- * @returns {Boolean}
- */
- validate: function(validator, $field, options, validatorName) {
- var type = $field.attr('type');
- if ('radio' === type || 'checkbox' === type) {
- var ns = validator.getNamespace();
- return validator
- .getFieldElements($field.attr('data-' + ns + '-field'))
- .filter(':checked')
- .length > 0;
- }
- if ('number' === type && $field.get(0).validity && $field.get(0).validity.badInput === true) {
- return true;
- }
- var value = validator.getFieldValue($field, validatorName);
- return $.trim(value) !== '';
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- numeric: {
- 'default': 'Please enter a valid float number'
- }
- }
- });
- FormValidation.Validator.numeric = {
- html5Attributes: {
- message: 'message',
- separator: 'separator', // deprecated
- thousandsseparator: 'thousandsSeparator',
- decimalseparator: 'decimalSeparator'
- },
- enableByHtml5: function($field) {
- return ('number' === $field.attr('type')) && ($field.attr('step') !== undefined) && ($field.attr('step') % 1 !== 0);
- },
- /**
- * Validate decimal number
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Consist of key:
- * - message: The invalid message
- * - thousandsSeparator: The thousands separator. It's empty by default
- * - separator, decimalSeparator: The decimal separator. It's '.' by default
- * The separator option is deprecated and should be replaced with decimalSeparator
- * @returns {Boolean}
- */
- validate: function(validator, $field, options, validatorName) {
- if (this.enableByHtml5($field) && $field.get(0).validity && $field.get(0).validity.badInput === true) {
- return false;
- }
- var value = validator.getFieldValue($field, validatorName);
- if (value === '') {
- return true;
- }
- var decimalSeparator = options.separator || options.decimalSeparator || '.',
- thousandsSeparator = options.thousandsSeparator || '';
- // Support preceding zero numbers such as .5, -.5
- if (value.substr(0, 1) === decimalSeparator) {
- value = '0' + decimalSeparator + value.substr(1);
- } else if (value.substr(0, 2) === '-' + decimalSeparator) {
- value = '-0' + decimalSeparator + value.substr(2);
- }
- decimalSeparator = (decimalSeparator === '.') ? '\\.' : decimalSeparator;
- thousandsSeparator = (thousandsSeparator === '.') ? '\\.' : thousandsSeparator;
- var testRegexp = new RegExp('^-?[0-9]{1,3}(' + thousandsSeparator + '[0-9]{3})*(' + decimalSeparator + '[0-9]+)?$'),
- thousandsReplacer = new RegExp(thousandsSeparator, 'g');
- if (!testRegexp.test(value)) {
- return false;
- }
- // Replace thousands separator with blank
- if (thousandsSeparator) {
- value = value.replace(thousandsReplacer, '');
- }
- // Replace decimal separator with a dot
- if (decimalSeparator) {
- value = value.replace(decimalSeparator, '.');
- }
- return !isNaN(parseFloat(value)) && isFinite(value);
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- promise: {
- 'default': 'Please enter a valid value'
- }
- }
- });
- FormValidation.Validator.promise = {
- priority: 999,
- html5Attributes: {
- message: 'message',
- promise: 'promise'
- },
- /**
- * Return result from a jQuery's Deferred object
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Can consist of the following keys:
- * - promise: The method that passes parameters:
- * promise: function(fieldValue, validator, $field) {
- * // fieldValue is the value of field
- * // validator is instance of FormValidation.Base
- * // $field is the field element
- *
- * var dfd = new $.Deferred();
- *
- * // Do something ...
- *
- * // Resolve when particular task is done
- * dfd.resolve({
- * valid: true or false, // Required
- * message: 'Other message', // Optional
- * key: value // You can attach more data to reuse later
- * });
- *
- * // You can reject if there's error
- * dfd.reject({
- * message: 'Other message', // Optional
- * key: value // You can attach more data to reuse later
- * });
- *
- * return dfd.promise();
- * }
- * - message: The invalid message
- * @returns {Deferred}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName),
- dfd = new $.Deferred(),
- promise = FormValidation.Helper.call(options.promise, [value, validator, $field]);
- promise
- .done(function(result) {
- dfd.resolve($field, validatorName, result);
- })
- .fail(function(result) {
- result = result || {};
- result.valid = false;
- dfd.resolve($field, validatorName, result);
- });
- return dfd;
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- regexp: {
- 'default': 'Please enter a value matching the pattern'
- }
- }
- });
- FormValidation.Validator.regexp = {
- html5Attributes: {
- message: 'message',
- flags: 'flags',
- regexp: 'regexp'
- },
- enableByHtml5: function($field) {
- var pattern = $field.attr('pattern');
- if (pattern) {
- return {
- regexp: pattern
- };
- }
- return false;
- },
- /**
- * Check if the element value matches given regular expression
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Consists of the following key:
- * - regexp: The regular expression you need to check
- * - flags: If specified, flags can have any combination of Javascript regular expression flags such as:
- * g: global match
- * i: ignore case
- * m: multiple line
- * @returns {Boolean}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName);
- if (value === '') {
- return true;
- }
- var regexp = ('string' === typeof options.regexp)
- ? (options.flags ? new RegExp(options.regexp, options.flags) : new RegExp(options.regexp))
- : options.regexp;
- return regexp.test(value);
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- remote: {
- 'default': 'Please enter a valid value'
- }
- }
- });
- FormValidation.Validator.remote = {
- priority: 1000,
- html5Attributes: {
- async: 'async',
- crossdomain: 'crossDomain',
- data: 'data',
- datatype: 'dataType',
- delay: 'delay',
- message: 'message',
- name: 'name',
- type: 'type',
- url: 'url',
- validkey: 'validKey'
- },
- /**
- * Destroy the timer when destroying the FormValidation (using validator.destroy() method)
- */
- destroy: function(validator, $field, options, validatorName) {
- var ns = validator.getNamespace(),
- timer = $field.data(ns + '.' + validatorName + '.timer');
- if (timer) {
- clearTimeout(timer);
- $field.removeData(ns + '.' + validatorName + '.timer');
- }
- },
- /**
- * Request a remote server to check the input value
- *
- * @param {FormValidation.Base} validator Plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Can consist of the following keys:
- * - async {Boolean} [optional] Indicate the Ajax request will be asynchronous or not. It's true by default
- * - crossDomain {Boolean} [optional]
- * - data {Object|Function} [optional]: By default, it will take the value
- * {
- * <fieldName>: <fieldValue>
- * }
- * - dataType {String} [optional]: The type of data which is returned by remote server.
- * It can be json (default), text, script
- * - delay {Number} [optional]
- * - headers {String[]} [optional]: Additional headers
- * - message {String} [optional]: The invalid message
- * - name {String} [optional]: Override the field name for the request.
- * - type {String} [optional] Can be GET or POST (default)
- * - url {String|Function}
- * - validKey {String} [optional]: The valid key. It's "valid" by default
- * This is useful when connecting to external remote server or APIs provided by 3rd parties
- * @returns {Deferred}
- */
- validate: function(validator, $field, options, validatorName) {
- var ns = validator.getNamespace(),
- value = validator.getFieldValue($field, validatorName),
- dfd = new $.Deferred();
- if (value === '') {
- dfd.resolve($field, validatorName, { valid: true });
- return dfd;
- }
- var name = $field.attr('data-' + ns + '-field'),
- data = options.data || {},
- url = options.url,
- validKey = options.validKey || 'valid';
- // Support dynamic data
- if ('function' === typeof data) {
- data = data.call(this, validator, $field, value);
- }
- // Parse string data from HTML5 attribute
- if ('string' === typeof data) {
- data = JSON.parse(data);
- }
- // Support dynamic url
- if ('function' === typeof url) {
- url = url.call(this, validator, $field, value);
- }
- data[options.name || name] = value;
- var ajaxOptions = {
- async: options.async === null || options.async === true || options.async === 'true',
- data: data,
- dataType: options.dataType || 'json',
- headers: options.headers || {},
- type: options.type || 'GET',
- url: url
- };
- if (options.crossDomain !== null) {
- ajaxOptions.crossDomain = (options.crossDomain === true || options.crossDomain === 'true');
- }
- function runCallback() {
- var xhr = $.ajax(ajaxOptions);
- xhr
- .success(function(response) {
- response.valid = (response[validKey] === true || response[validKey] === 'true')
- ? true
- : (response[validKey] === false || response[validKey] === 'false' ? false : null);
- dfd.resolve($field, validatorName, response);
- })
- .error(function(response) {
- dfd.resolve($field, validatorName, {
- valid: false
- });
- });
- dfd.fail(function() {
- xhr.abort();
- });
- return dfd;
- }
-
- if (options.delay) {
- // Since the form might have multiple fields with the same name
- // I have to attach the timer to the field element
- if ($field.data(ns + '.' + validatorName + '.timer')) {
- clearTimeout($field.data(ns + '.' + validatorName + '.timer'));
- }
- $field.data(ns + '.' + validatorName + '.timer', setTimeout(runCallback, options.delay));
- return dfd;
- } else {
- return runCallback();
- }
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- stringLength: {
- 'default': 'Please enter a value with valid length',
- less: 'Please enter less than %s characters',
- more: 'Please enter more than %s characters',
- between: 'Please enter value between %s and %s characters long'
- }
- }
- });
- FormValidation.Validator.stringLength = {
- html5Attributes: {
- message: 'message',
- min: 'min',
- max: 'max',
- trim: 'trim',
- utf8bytes: 'utf8Bytes'
- },
- enableByHtml5: function($field) {
- var options = {},
- maxLength = $field.attr('maxlength'),
- minLength = $field.attr('minlength');
- if (maxLength) {
- options.max = parseInt(maxLength, 10);
- }
- if (minLength) {
- options.min = parseInt(minLength, 10);
- }
- return $.isEmptyObject(options) ? false : options;
- },
- /**
- * Check if the length of element value is less or more than given number
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options Consists of following keys:
- * - min
- * - max
- * At least one of two keys is required
- * The min, max keys define the number which the field value compares to. min, max can be
- * - A number
- * - Name of field which its value defines the number
- * - Name of callback function that returns the number
- * - A callback function that returns the number
- *
- * - message: The invalid message
- * - trim: Indicate the length will be calculated after trimming the value or not. It is false, by default
- * - utf8bytes: Evaluate string length in UTF-8 bytes, default to false
- * @returns {Object}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName);
- if (options.trim === true || options.trim === 'true') {
- value = $.trim(value);
- }
- if (value === '') {
- return true;
- }
- var locale = validator.getLocale(),
- min = $.isNumeric(options.min) ? options.min : validator.getDynamicOption($field, options.min),
- max = $.isNumeric(options.max) ? options.max : validator.getDynamicOption($field, options.max),
- // Credit to http://stackoverflow.com/a/23329386 (@lovasoa) for UTF-8 byte length code
- utf8Length = function(str) {
- var s = str.length;
- for (var i = str.length - 1; i >= 0; i--) {
- var code = str.charCodeAt(i);
- if (code > 0x7f && code <= 0x7ff) {
- s++;
- } else if (code > 0x7ff && code <= 0xffff) {
- s += 2;
- }
- if (code >= 0xDC00 && code <= 0xDFFF) {
- i--;
- }
- }
- return s;
- },
- length = options.utf8Bytes ? utf8Length(value) : value.length,
- isValid = true,
- message = options.message || FormValidation.I18n[locale].stringLength['default'];
- if ((min && length < parseInt(min, 10)) || (max && length > parseInt(max, 10))) {
- isValid = false;
- }
- switch (true) {
- case (!!min && !!max):
- message = FormValidation.Helper.format(options.message || FormValidation.I18n[locale].stringLength.between, [parseInt(min, 10), parseInt(max, 10)]);
- break;
- case (!!min):
- message = FormValidation.Helper.format(options.message || FormValidation.I18n[locale].stringLength.more, parseInt(min, 10) - 1);
- break;
- case (!!max):
- message = FormValidation.Helper.format(options.message || FormValidation.I18n[locale].stringLength.less, parseInt(max, 10) + 1);
- break;
- default:
- break;
- }
- return {
- valid: isValid,
- message: message
- };
- }
- };
- }(jQuery));
- ;(function($) {
- FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, {
- 'en_US': {
- uri: {
- 'default': 'Please enter a valid URI'
- }
- }
- });
- FormValidation.Validator.uri = {
- html5Attributes: {
- message: 'message',
- allowlocal: 'allowLocal',
- allowemptyprotocol: 'allowEmptyProtocol',
- protocol: 'protocol'
- },
- enableByHtml5: function($field) {
- return ('url' === $field.attr('type'));
- },
- /**
- * Return true if the input value is a valid URL
- *
- * @param {FormValidation.Base} validator The validator plugin instance
- * @param {jQuery} $field Field element
- * @param {Object} options
- * - message: The error message
- * - allowLocal: Allow the private and local network IP. Default to false
- * - allowEmptyProtocol: Allow the URI without protocol. Default to false
- * - protocol: The protocols, separated by a comma. Default to "http, https, ftp"
- * @returns {Boolean}
- */
- validate: function(validator, $field, options, validatorName) {
- var value = validator.getFieldValue($field, validatorName);
- if (value === '') {
- return true;
- }
- // Credit to https://gist.github.com/dperini/729294
- //
- // Regular Expression for URL validation
- //
- // Author: Diego Perini
- // Updated: 2010/12/05
- //
- // the regular expression composed & commented
- // could be easily tweaked for RFC compliance,
- // it was expressly modified to fit & satisfy
- // these test for an URL shortener:
- //
- // http://mathiasbynens.be/demo/url-regex
- //
- // Notes on possible differences from a standard/generic validation:
- //
- // - utf-8 char class take in consideration the full Unicode range
- // - TLDs are mandatory unless `allowLocal` is true
- // - protocols have been restricted to ftp, http and https only as requested
- //
- // Changes:
- //
- // - IP address dotted notation validation, range: 1.0.0.0 - 223.255.255.255
- // first and last IP address of each class is considered invalid
- // (since they are broadcast/network addresses)
- //
- // - Added exclusion of private, reserved and/or local networks ranges
- // unless `allowLocal` is true
- //
- // - Added possibility of choosing a custom protocol
- //
- // - Add option to validate without protocol
- //
- var allowLocal = options.allowLocal === true || options.allowLocal === 'true',
- allowEmptyProtocol = options.allowEmptyProtocol === true || options.allowEmptyProtocol === 'true',
- protocol = (options.protocol || 'http, https, ftp').split(',').join('|').replace(/\s/g, ''),
- urlExp = new RegExp(
- "^" +
- // protocol identifier
- "(?:(?:" + protocol + ")://)" +
- // allow empty protocol
- (allowEmptyProtocol ? '?' : '') +
- // user:pass authentication
- "(?:\\S+(?::\\S*)?@)?" +
- "(?:" +
- // IP address exclusion
- // private & local networks
- (allowLocal
- ? ''
- : ("(?!(?:10|127)(?:\\.\\d{1,3}){3})" +
- "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" +
- "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})")) +
- // IP address dotted notation octets
- // excludes loopback network 0.0.0.0
- // excludes reserved space >= 224.0.0.0
- // excludes network & broadcast addresses
- // (first & last IP address of each class)
- "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
- "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
- "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
- "|" +
- // host name
- "(?:(?:[a-z\\u00a1-\\uffff0-9]-?)*[a-z\\u00a1-\\uffff0-9]+)" +
- // domain name
- "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-?)*[a-z\\u00a1-\\uffff0-9])*" +
- // TLD identifier
- "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
- // Allow intranet sites (no TLD) if `allowLocal` is true
- (allowLocal ? '?' : '') +
- ")" +
- // port number
- "(?::\\d{2,5})?" +
- // resource path
- "(?:/[^\\s]*)?" +
- "$", "i"
- );
- return urlExp.test(value);
- }
- };
- }(jQuery));
|