validator_test.go 218 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765
  1. package validator
  2. import (
  3. "bytes"
  4. "context"
  5. "database/sql"
  6. "database/sql/driver"
  7. "encoding/base64"
  8. "encoding/json"
  9. "fmt"
  10. "path/filepath"
  11. "reflect"
  12. "strings"
  13. "testing"
  14. "time"
  15. "github.com/go-playground/locales/en"
  16. "github.com/go-playground/locales/fr"
  17. "github.com/go-playground/locales/nl"
  18. ut "github.com/go-playground/universal-translator"
  19. . "gopkg.in/go-playground/assert.v1"
  20. )
  21. // NOTES:
  22. // - Run "go test" to run tests
  23. // - Run "gocov test | gocov report" to report on test converage by file
  24. // - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never called
  25. //
  26. // or
  27. //
  28. // -- may be a good idea to change to output path to somewherelike /tmp
  29. // go test -coverprofile cover.out && go tool cover -html=cover.out -o cover.html
  30. //
  31. //
  32. // go test -cpuprofile cpu.out
  33. // ./validator.test -test.bench=. -test.cpuprofile=cpu.prof
  34. // go tool pprof validator.test cpu.prof
  35. //
  36. //
  37. // go test -memprofile mem.out
  38. type I interface {
  39. Foo() string
  40. }
  41. type Impl struct {
  42. F string `validate:"len=3"`
  43. }
  44. func (i *Impl) Foo() string {
  45. return i.F
  46. }
  47. type SubTest struct {
  48. Test string `validate:"required"`
  49. }
  50. type TestInterface struct {
  51. Iface I
  52. }
  53. type TestString struct {
  54. BlankTag string `validate:""`
  55. Required string `validate:"required"`
  56. Len string `validate:"len=10"`
  57. Min string `validate:"min=1"`
  58. Max string `validate:"max=10"`
  59. MinMax string `validate:"min=1,max=10"`
  60. Lt string `validate:"lt=10"`
  61. Lte string `validate:"lte=10"`
  62. Gt string `validate:"gt=10"`
  63. Gte string `validate:"gte=10"`
  64. OmitEmpty string `validate:"omitempty,min=1,max=10"`
  65. Sub *SubTest
  66. SubIgnore *SubTest `validate:"-"`
  67. Anonymous struct {
  68. A string `validate:"required"`
  69. }
  70. Iface I
  71. }
  72. type TestUint64 struct {
  73. Required uint64 `validate:"required"`
  74. Len uint64 `validate:"len=10"`
  75. Min uint64 `validate:"min=1"`
  76. Max uint64 `validate:"max=10"`
  77. MinMax uint64 `validate:"min=1,max=10"`
  78. OmitEmpty uint64 `validate:"omitempty,min=1,max=10"`
  79. }
  80. type TestFloat64 struct {
  81. Required float64 `validate:"required"`
  82. Len float64 `validate:"len=10"`
  83. Min float64 `validate:"min=1"`
  84. Max float64 `validate:"max=10"`
  85. MinMax float64 `validate:"min=1,max=10"`
  86. Lte float64 `validate:"lte=10"`
  87. OmitEmpty float64 `validate:"omitempty,min=1,max=10"`
  88. }
  89. type TestSlice struct {
  90. Required []int `validate:"required"`
  91. Len []int `validate:"len=10"`
  92. Min []int `validate:"min=1"`
  93. Max []int `validate:"max=10"`
  94. MinMax []int `validate:"min=1,max=10"`
  95. OmitEmpty []int `validate:"omitempty,min=1,max=10"`
  96. }
  97. func AssertError(t *testing.T, err error, nsKey, structNsKey, field, structField, expectedTag string) {
  98. errs := err.(ValidationErrors)
  99. found := false
  100. var fe FieldError
  101. for i := 0; i < len(errs); i++ {
  102. if errs[i].Namespace() == nsKey && errs[i].StructNamespace() == structNsKey {
  103. found = true
  104. fe = errs[i]
  105. break
  106. }
  107. }
  108. EqualSkip(t, 2, found, true)
  109. NotEqualSkip(t, 2, fe, nil)
  110. EqualSkip(t, 2, fe.Field(), field)
  111. EqualSkip(t, 2, fe.StructField(), structField)
  112. EqualSkip(t, 2, fe.Tag(), expectedTag)
  113. }
  114. func AssertDeepError(t *testing.T, err error, nsKey, structNsKey, field, structField, expectedTag, actualTag string) {
  115. errs := err.(ValidationErrors)
  116. found := false
  117. var fe FieldError
  118. for i := 0; i < len(errs); i++ {
  119. if errs[i].Namespace() == nsKey && errs[i].StructNamespace() == structNsKey && errs[i].Tag() == expectedTag && errs[i].ActualTag() == actualTag {
  120. found = true
  121. fe = errs[i]
  122. break
  123. }
  124. }
  125. EqualSkip(t, 2, found, true)
  126. NotEqualSkip(t, 2, fe, nil)
  127. EqualSkip(t, 2, fe.Field(), field)
  128. EqualSkip(t, 2, fe.StructField(), structField)
  129. }
  130. func getError(err error, nsKey, structNsKey string) FieldError {
  131. errs := err.(ValidationErrors)
  132. var fe FieldError
  133. for i := 0; i < len(errs); i++ {
  134. if errs[i].Namespace() == nsKey && errs[i].StructNamespace() == structNsKey {
  135. fe = errs[i]
  136. break
  137. }
  138. }
  139. return fe
  140. }
  141. type valuer struct {
  142. Name string
  143. }
  144. func (v valuer) Value() (driver.Value, error) {
  145. if v.Name == "errorme" {
  146. panic("SQL Driver Valuer error: some kind of error")
  147. // return nil, errors.New("some kind of error")
  148. }
  149. if len(v.Name) == 0 {
  150. return nil, nil
  151. }
  152. return v.Name, nil
  153. }
  154. type MadeUpCustomType struct {
  155. FirstName string
  156. LastName string
  157. }
  158. func ValidateCustomType(field reflect.Value) interface{} {
  159. if cust, ok := field.Interface().(MadeUpCustomType); ok {
  160. if len(cust.FirstName) == 0 || len(cust.LastName) == 0 {
  161. return ""
  162. }
  163. return cust.FirstName + " " + cust.LastName
  164. }
  165. return ""
  166. }
  167. func OverrideIntTypeForSomeReason(field reflect.Value) interface{} {
  168. if i, ok := field.Interface().(int); ok {
  169. if i == 1 {
  170. return "1"
  171. }
  172. if i == 2 {
  173. return "12"
  174. }
  175. }
  176. return ""
  177. }
  178. type CustomMadeUpStruct struct {
  179. MadeUp MadeUpCustomType `validate:"required"`
  180. OverriddenInt int `validate:"gt=1"`
  181. }
  182. func ValidateValuerType(field reflect.Value) interface{} {
  183. if valuer, ok := field.Interface().(driver.Valuer); ok {
  184. val, err := valuer.Value()
  185. if err != nil {
  186. // handle the error how you want
  187. return nil
  188. }
  189. return val
  190. }
  191. return nil
  192. }
  193. type TestPartial struct {
  194. NoTag string
  195. BlankTag string `validate:""`
  196. Required string `validate:"required"`
  197. SubSlice []*SubTest `validate:"required,dive"`
  198. Sub *SubTest
  199. SubIgnore *SubTest `validate:"-"`
  200. Anonymous struct {
  201. A string `validate:"required"`
  202. ASubSlice []*SubTest `validate:"required,dive"`
  203. SubAnonStruct []struct {
  204. Test string `validate:"required"`
  205. OtherTest string `validate:"required"`
  206. } `validate:"required,dive"`
  207. }
  208. }
  209. type TestStruct struct {
  210. String string `validate:"required" json:"StringVal"`
  211. }
  212. func StructValidationTestStructSuccess(sl StructLevel) {
  213. st := sl.Current().Interface().(TestStruct)
  214. if st.String != "good value" {
  215. sl.ReportError(st.String, "StringVal", "String", "badvalueteststruct", "good value")
  216. }
  217. }
  218. func StructValidationTestStruct(sl StructLevel) {
  219. st := sl.Current().Interface().(TestStruct)
  220. if st.String != "bad value" {
  221. sl.ReportError(st.String, "StringVal", "String", "badvalueteststruct", "bad value")
  222. }
  223. }
  224. func StructValidationNoTestStructCustomName(sl StructLevel) {
  225. st := sl.Current().Interface().(TestStruct)
  226. if st.String != "bad value" {
  227. sl.ReportError(st.String, "String", "", "badvalueteststruct", "bad value")
  228. }
  229. }
  230. func StructValidationTestStructInvalid(sl StructLevel) {
  231. st := sl.Current().Interface().(TestStruct)
  232. if st.String != "bad value" {
  233. sl.ReportError(nil, "StringVal", "String", "badvalueteststruct", "bad value")
  234. }
  235. }
  236. func StructValidationTestStructReturnValidationErrors(sl StructLevel) {
  237. s := sl.Current().Interface().(TestStructReturnValidationErrors)
  238. errs := sl.Validator().Struct(s.Inner1.Inner2)
  239. if errs == nil {
  240. return
  241. }
  242. sl.ReportValidationErrors("Inner1.", "Inner1.", errs.(ValidationErrors))
  243. }
  244. func StructValidationTestStructReturnValidationErrors2(sl StructLevel) {
  245. s := sl.Current().Interface().(TestStructReturnValidationErrors)
  246. errs := sl.Validator().Struct(s.Inner1.Inner2)
  247. if errs == nil {
  248. return
  249. }
  250. sl.ReportValidationErrors("Inner1JSON.", "Inner1.", errs.(ValidationErrors))
  251. }
  252. type TestStructReturnValidationErrorsInner2 struct {
  253. String string `validate:"required" json:"JSONString"`
  254. }
  255. type TestStructReturnValidationErrorsInner1 struct {
  256. Inner2 *TestStructReturnValidationErrorsInner2
  257. }
  258. type TestStructReturnValidationErrors struct {
  259. Inner1 *TestStructReturnValidationErrorsInner1 `json:"Inner1JSON"`
  260. }
  261. type StructLevelInvalidErr struct {
  262. Value string
  263. }
  264. func StructLevelInvalidError(sl StructLevel) {
  265. top := sl.Top().Interface().(StructLevelInvalidErr)
  266. s := sl.Current().Interface().(StructLevelInvalidErr)
  267. if top.Value == s.Value {
  268. sl.ReportError(nil, "Value", "Value", "required", "")
  269. }
  270. }
  271. func TestStructLevelInvalidError(t *testing.T) {
  272. validate := New()
  273. validate.RegisterStructValidation(StructLevelInvalidError, StructLevelInvalidErr{})
  274. var test StructLevelInvalidErr
  275. err := validate.Struct(test)
  276. NotEqual(t, err, nil)
  277. errs, ok := err.(ValidationErrors)
  278. Equal(t, ok, true)
  279. fe := errs[0]
  280. Equal(t, fe.Field(), "Value")
  281. Equal(t, fe.StructField(), "Value")
  282. Equal(t, fe.Namespace(), "StructLevelInvalidErr.Value")
  283. Equal(t, fe.StructNamespace(), "StructLevelInvalidErr.Value")
  284. Equal(t, fe.Tag(), "required")
  285. Equal(t, fe.ActualTag(), "required")
  286. Equal(t, fe.Kind(), reflect.Invalid)
  287. Equal(t, fe.Type(), reflect.TypeOf(nil))
  288. }
  289. func TestNameNamespace(t *testing.T) {
  290. type Inner2Namespace struct {
  291. String []string `validate:"dive,required" json:"JSONString"`
  292. }
  293. type Inner1Namespace struct {
  294. Inner2 *Inner2Namespace `json:"Inner2JSON"`
  295. }
  296. type Namespace struct {
  297. Inner1 *Inner1Namespace `json:"Inner1JSON"`
  298. }
  299. validate := New()
  300. validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
  301. name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
  302. if name == "-" {
  303. return ""
  304. }
  305. return name
  306. })
  307. i2 := &Inner2Namespace{String: []string{"ok", "ok", "ok"}}
  308. i1 := &Inner1Namespace{Inner2: i2}
  309. ns := &Namespace{Inner1: i1}
  310. errs := validate.Struct(ns)
  311. Equal(t, errs, nil)
  312. i2.String[1] = ""
  313. errs = validate.Struct(ns)
  314. NotEqual(t, errs, nil)
  315. ve := errs.(ValidationErrors)
  316. Equal(t, len(ve), 1)
  317. AssertError(t, errs, "Namespace.Inner1JSON.Inner2JSON.JSONString[1]", "Namespace.Inner1.Inner2.String[1]", "JSONString[1]", "String[1]", "required")
  318. fe := getError(ve, "Namespace.Inner1JSON.Inner2JSON.JSONString[1]", "Namespace.Inner1.Inner2.String[1]")
  319. NotEqual(t, fe, nil)
  320. Equal(t, fe.Field(), "JSONString[1]")
  321. Equal(t, fe.StructField(), "String[1]")
  322. Equal(t, fe.Namespace(), "Namespace.Inner1JSON.Inner2JSON.JSONString[1]")
  323. Equal(t, fe.StructNamespace(), "Namespace.Inner1.Inner2.String[1]")
  324. }
  325. func TestAnonymous(t *testing.T) {
  326. validate := New()
  327. validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
  328. name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
  329. if name == "-" {
  330. return ""
  331. }
  332. return name
  333. })
  334. type Test struct {
  335. Anonymous struct {
  336. A string `validate:"required" json:"EH"`
  337. }
  338. AnonymousB struct {
  339. B string `validate:"required" json:"BEE"`
  340. }
  341. anonymousC struct {
  342. c string `validate:"required"`
  343. }
  344. }
  345. tst := &Test{
  346. Anonymous: struct {
  347. A string `validate:"required" json:"EH"`
  348. }{
  349. A: "1",
  350. },
  351. AnonymousB: struct {
  352. B string `validate:"required" json:"BEE"`
  353. }{
  354. B: "",
  355. },
  356. anonymousC: struct {
  357. c string `validate:"required"`
  358. }{
  359. c: "",
  360. },
  361. }
  362. err := validate.Struct(tst)
  363. NotEqual(t, err, nil)
  364. errs := err.(ValidationErrors)
  365. Equal(t, len(errs), 1)
  366. AssertError(t, errs, "Test.AnonymousB.BEE", "Test.AnonymousB.B", "BEE", "B", "required")
  367. fe := getError(errs, "Test.AnonymousB.BEE", "Test.AnonymousB.B")
  368. NotEqual(t, fe, nil)
  369. Equal(t, fe.Field(), "BEE")
  370. Equal(t, fe.StructField(), "B")
  371. s := struct {
  372. c string `validate:"required"`
  373. }{
  374. c: "",
  375. }
  376. err = validate.Struct(s)
  377. Equal(t, err, nil)
  378. }
  379. func TestAnonymousSameStructDifferentTags(t *testing.T) {
  380. validate := New()
  381. validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
  382. name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
  383. if name == "-" {
  384. return ""
  385. }
  386. return name
  387. })
  388. type Test struct {
  389. A interface{}
  390. }
  391. tst := &Test{
  392. A: struct {
  393. A string `validate:"required"`
  394. }{
  395. A: "",
  396. },
  397. }
  398. err := validate.Struct(tst)
  399. NotEqual(t, err, nil)
  400. errs := err.(ValidationErrors)
  401. Equal(t, len(errs), 1)
  402. AssertError(t, errs, "Test.A.A", "Test.A.A", "A", "A", "required")
  403. tst = &Test{
  404. A: struct {
  405. A string `validate:"omitempty,required"`
  406. }{
  407. A: "",
  408. },
  409. }
  410. err = validate.Struct(tst)
  411. Equal(t, err, nil)
  412. }
  413. func TestStructLevelReturnValidationErrors(t *testing.T) {
  414. validate := New()
  415. validate.RegisterStructValidation(StructValidationTestStructReturnValidationErrors, TestStructReturnValidationErrors{})
  416. inner2 := &TestStructReturnValidationErrorsInner2{
  417. String: "I'm HERE",
  418. }
  419. inner1 := &TestStructReturnValidationErrorsInner1{
  420. Inner2: inner2,
  421. }
  422. val := &TestStructReturnValidationErrors{
  423. Inner1: inner1,
  424. }
  425. errs := validate.Struct(val)
  426. Equal(t, errs, nil)
  427. inner2.String = ""
  428. errs = validate.Struct(val)
  429. NotEqual(t, errs, nil)
  430. Equal(t, len(errs.(ValidationErrors)), 2)
  431. AssertError(t, errs, "TestStructReturnValidationErrors.Inner1.Inner2.String", "TestStructReturnValidationErrors.Inner1.Inner2.String", "String", "String", "required")
  432. // this is an extra error reported from struct validation
  433. AssertError(t, errs, "TestStructReturnValidationErrors.Inner1.TestStructReturnValidationErrorsInner2.String", "TestStructReturnValidationErrors.Inner1.TestStructReturnValidationErrorsInner2.String", "String", "String", "required")
  434. }
  435. func TestStructLevelReturnValidationErrorsWithJSON(t *testing.T) {
  436. validate := New()
  437. validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
  438. name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
  439. if name == "-" {
  440. return ""
  441. }
  442. return name
  443. })
  444. validate.RegisterStructValidation(StructValidationTestStructReturnValidationErrors2, TestStructReturnValidationErrors{})
  445. inner2 := &TestStructReturnValidationErrorsInner2{
  446. String: "I'm HERE",
  447. }
  448. inner1 := &TestStructReturnValidationErrorsInner1{
  449. Inner2: inner2,
  450. }
  451. val := &TestStructReturnValidationErrors{
  452. Inner1: inner1,
  453. }
  454. errs := validate.Struct(val)
  455. Equal(t, errs, nil)
  456. inner2.String = ""
  457. errs = validate.Struct(val)
  458. NotEqual(t, errs, nil)
  459. Equal(t, len(errs.(ValidationErrors)), 2)
  460. AssertError(t, errs, "TestStructReturnValidationErrors.Inner1JSON.Inner2.JSONString", "TestStructReturnValidationErrors.Inner1.Inner2.String", "JSONString", "String", "required")
  461. // this is an extra error reported from struct validation, it's a badly formatted one, but on purpose
  462. AssertError(t, errs, "TestStructReturnValidationErrors.Inner1JSON.TestStructReturnValidationErrorsInner2.JSONString", "TestStructReturnValidationErrors.Inner1.TestStructReturnValidationErrorsInner2.String", "JSONString", "String", "required")
  463. fe := getError(errs, "TestStructReturnValidationErrors.Inner1JSON.Inner2.JSONString", "TestStructReturnValidationErrors.Inner1.Inner2.String")
  464. NotEqual(t, fe, nil)
  465. // check for proper JSON namespace
  466. Equal(t, fe.Field(), "JSONString")
  467. Equal(t, fe.StructField(), "String")
  468. Equal(t, fe.Namespace(), "TestStructReturnValidationErrors.Inner1JSON.Inner2.JSONString")
  469. Equal(t, fe.StructNamespace(), "TestStructReturnValidationErrors.Inner1.Inner2.String")
  470. fe = getError(errs, "TestStructReturnValidationErrors.Inner1JSON.TestStructReturnValidationErrorsInner2.JSONString", "TestStructReturnValidationErrors.Inner1.TestStructReturnValidationErrorsInner2.String")
  471. NotEqual(t, fe, nil)
  472. // check for proper JSON namespace
  473. Equal(t, fe.Field(), "JSONString")
  474. Equal(t, fe.StructField(), "String")
  475. Equal(t, fe.Namespace(), "TestStructReturnValidationErrors.Inner1JSON.TestStructReturnValidationErrorsInner2.JSONString")
  476. Equal(t, fe.StructNamespace(), "TestStructReturnValidationErrors.Inner1.TestStructReturnValidationErrorsInner2.String")
  477. }
  478. func TestStructLevelValidations(t *testing.T) {
  479. v1 := New()
  480. v1.RegisterStructValidation(StructValidationTestStruct, TestStruct{})
  481. tst := &TestStruct{
  482. String: "good value",
  483. }
  484. errs := v1.Struct(tst)
  485. NotEqual(t, errs, nil)
  486. AssertError(t, errs, "TestStruct.StringVal", "TestStruct.String", "StringVal", "String", "badvalueteststruct")
  487. v2 := New()
  488. v2.RegisterStructValidation(StructValidationNoTestStructCustomName, TestStruct{})
  489. errs = v2.Struct(tst)
  490. NotEqual(t, errs, nil)
  491. AssertError(t, errs, "TestStruct.String", "TestStruct.String", "String", "String", "badvalueteststruct")
  492. v3 := New()
  493. v3.RegisterStructValidation(StructValidationTestStructInvalid, TestStruct{})
  494. errs = v3.Struct(tst)
  495. NotEqual(t, errs, nil)
  496. AssertError(t, errs, "TestStruct.StringVal", "TestStruct.String", "StringVal", "String", "badvalueteststruct")
  497. v4 := New()
  498. v4.RegisterStructValidation(StructValidationTestStructSuccess, TestStruct{})
  499. errs = v4.Struct(tst)
  500. Equal(t, errs, nil)
  501. }
  502. func TestAliasTags(t *testing.T) {
  503. validate := New()
  504. validate.RegisterAlias("iscoloralias", "hexcolor|rgb|rgba|hsl|hsla")
  505. s := "rgb(255,255,255)"
  506. errs := validate.Var(s, "iscoloralias")
  507. Equal(t, errs, nil)
  508. s = ""
  509. errs = validate.Var(s, "omitempty,iscoloralias")
  510. Equal(t, errs, nil)
  511. s = "rgb(255,255,0)"
  512. errs = validate.Var(s, "iscoloralias,len=5")
  513. NotEqual(t, errs, nil)
  514. AssertError(t, errs, "", "", "", "", "len")
  515. type Test struct {
  516. Color string `validate:"iscoloralias"`
  517. }
  518. tst := &Test{
  519. Color: "#000",
  520. }
  521. errs = validate.Struct(tst)
  522. Equal(t, errs, nil)
  523. tst.Color = "cfvre"
  524. errs = validate.Struct(tst)
  525. NotEqual(t, errs, nil)
  526. AssertError(t, errs, "Test.Color", "Test.Color", "Color", "Color", "iscoloralias")
  527. fe := getError(errs, "Test.Color", "Test.Color")
  528. NotEqual(t, fe, nil)
  529. Equal(t, fe.ActualTag(), "hexcolor|rgb|rgba|hsl|hsla")
  530. validate.RegisterAlias("req", "required,dive,iscoloralias")
  531. arr := []string{"val1", "#fff", "#000"}
  532. errs = validate.Var(arr, "req")
  533. NotEqual(t, errs, nil)
  534. AssertError(t, errs, "[0]", "[0]", "[0]", "[0]", "iscoloralias")
  535. PanicMatches(t, func() { validate.RegisterAlias("exists!", "gt=5,lt=10") }, "Alias 'exists!' either contains restricted characters or is the same as a restricted tag needed for normal operation")
  536. }
  537. func TestNilValidator(t *testing.T) {
  538. type TestStruct struct {
  539. Test string `validate:"required"`
  540. }
  541. ts := TestStruct{}
  542. var val *Validate
  543. fn := func(fl FieldLevel) bool {
  544. return fl.Parent().String() == fl.Field().String()
  545. }
  546. PanicMatches(t, func() { val.RegisterCustomTypeFunc(ValidateCustomType, MadeUpCustomType{}) }, "runtime error: invalid memory address or nil pointer dereference")
  547. PanicMatches(t, func() { val.RegisterValidation("something", fn) }, "runtime error: invalid memory address or nil pointer dereference")
  548. PanicMatches(t, func() { val.Var(ts.Test, "required") }, "runtime error: invalid memory address or nil pointer dereference")
  549. PanicMatches(t, func() { val.VarWithValue("test", ts.Test, "required") }, "runtime error: invalid memory address or nil pointer dereference")
  550. PanicMatches(t, func() { val.Struct(ts) }, "runtime error: invalid memory address or nil pointer dereference")
  551. PanicMatches(t, func() { val.StructExcept(ts, "Test") }, "runtime error: invalid memory address or nil pointer dereference")
  552. PanicMatches(t, func() { val.StructPartial(ts, "Test") }, "runtime error: invalid memory address or nil pointer dereference")
  553. }
  554. func TestStructPartial(t *testing.T) {
  555. p1 := []string{
  556. "NoTag",
  557. "Required",
  558. }
  559. p2 := []string{
  560. "SubSlice[0].Test",
  561. "Sub",
  562. "SubIgnore",
  563. "Anonymous.A",
  564. }
  565. p3 := []string{
  566. "SubTest.Test",
  567. }
  568. p4 := []string{
  569. "A",
  570. }
  571. tPartial := &TestPartial{
  572. NoTag: "NoTag",
  573. Required: "Required",
  574. SubSlice: []*SubTest{
  575. {
  576. Test: "Required",
  577. },
  578. {
  579. Test: "Required",
  580. },
  581. },
  582. Sub: &SubTest{
  583. Test: "1",
  584. },
  585. SubIgnore: &SubTest{
  586. Test: "",
  587. },
  588. Anonymous: struct {
  589. A string `validate:"required"`
  590. ASubSlice []*SubTest `validate:"required,dive"`
  591. SubAnonStruct []struct {
  592. Test string `validate:"required"`
  593. OtherTest string `validate:"required"`
  594. } `validate:"required,dive"`
  595. }{
  596. A: "1",
  597. ASubSlice: []*SubTest{
  598. {
  599. Test: "Required",
  600. },
  601. {
  602. Test: "Required",
  603. },
  604. },
  605. SubAnonStruct: []struct {
  606. Test string `validate:"required"`
  607. OtherTest string `validate:"required"`
  608. }{
  609. {"Required", "RequiredOther"},
  610. {"Required", "RequiredOther"},
  611. },
  612. },
  613. }
  614. validate := New()
  615. // the following should all return no errors as everything is valid in
  616. // the default state
  617. errs := validate.StructPartialCtx(context.Background(), tPartial, p1...)
  618. Equal(t, errs, nil)
  619. errs = validate.StructPartial(tPartial, p2...)
  620. Equal(t, errs, nil)
  621. // this isn't really a robust test, but is ment to illustrate the ANON CASE below
  622. errs = validate.StructPartial(tPartial.SubSlice[0], p3...)
  623. Equal(t, errs, nil)
  624. errs = validate.StructExceptCtx(context.Background(), tPartial, p1...)
  625. Equal(t, errs, nil)
  626. errs = validate.StructExcept(tPartial, p2...)
  627. Equal(t, errs, nil)
  628. // mod tParial for required feild and re-test making sure invalid fields are NOT required:
  629. tPartial.Required = ""
  630. errs = validate.StructExcept(tPartial, p1...)
  631. Equal(t, errs, nil)
  632. errs = validate.StructPartial(tPartial, p2...)
  633. Equal(t, errs, nil)
  634. // inversion and retesting Partial to generate failures:
  635. errs = validate.StructPartial(tPartial, p1...)
  636. NotEqual(t, errs, nil)
  637. AssertError(t, errs, "TestPartial.Required", "TestPartial.Required", "Required", "Required", "required")
  638. errs = validate.StructExcept(tPartial, p2...)
  639. AssertError(t, errs, "TestPartial.Required", "TestPartial.Required", "Required", "Required", "required")
  640. // reset Required field, and set nested struct
  641. tPartial.Required = "Required"
  642. tPartial.Anonymous.A = ""
  643. // will pass as unset feilds is not going to be tested
  644. errs = validate.StructPartial(tPartial, p1...)
  645. Equal(t, errs, nil)
  646. errs = validate.StructExcept(tPartial, p2...)
  647. Equal(t, errs, nil)
  648. // ANON CASE the response here is strange, it clearly does what it is being told to
  649. errs = validate.StructExcept(tPartial.Anonymous, p4...)
  650. Equal(t, errs, nil)
  651. // will fail as unset feild is tested
  652. errs = validate.StructPartial(tPartial, p2...)
  653. NotEqual(t, errs, nil)
  654. AssertError(t, errs, "TestPartial.Anonymous.A", "TestPartial.Anonymous.A", "A", "A", "required")
  655. errs = validate.StructExcept(tPartial, p1...)
  656. NotEqual(t, errs, nil)
  657. AssertError(t, errs, "TestPartial.Anonymous.A", "TestPartial.Anonymous.A", "A", "A", "required")
  658. // reset nested struct and unset struct in slice
  659. tPartial.Anonymous.A = "Required"
  660. tPartial.SubSlice[0].Test = ""
  661. // these will pass as unset item is NOT tested
  662. errs = validate.StructPartial(tPartial, p1...)
  663. Equal(t, errs, nil)
  664. errs = validate.StructExcept(tPartial, p2...)
  665. Equal(t, errs, nil)
  666. // these will fail as unset item IS tested
  667. errs = validate.StructExcept(tPartial, p1...)
  668. AssertError(t, errs, "TestPartial.SubSlice[0].Test", "TestPartial.SubSlice[0].Test", "Test", "Test", "required")
  669. Equal(t, len(errs.(ValidationErrors)), 1)
  670. errs = validate.StructPartial(tPartial, p2...)
  671. NotEqual(t, errs, nil)
  672. AssertError(t, errs, "TestPartial.SubSlice[0].Test", "TestPartial.SubSlice[0].Test", "Test", "Test", "required")
  673. Equal(t, len(errs.(ValidationErrors)), 1)
  674. // Unset second slice member concurrently to test dive behavior:
  675. tPartial.SubSlice[1].Test = ""
  676. errs = validate.StructPartial(tPartial, p1...)
  677. Equal(t, errs, nil)
  678. // NOTE: When specifying nested items, it is still the users responsibility
  679. // to specify the dive tag, the library does not override this.
  680. errs = validate.StructExcept(tPartial, p2...)
  681. NotEqual(t, errs, nil)
  682. AssertError(t, errs, "TestPartial.SubSlice[1].Test", "TestPartial.SubSlice[1].Test", "Test", "Test", "required")
  683. errs = validate.StructExcept(tPartial, p1...)
  684. Equal(t, len(errs.(ValidationErrors)), 2)
  685. AssertError(t, errs, "TestPartial.SubSlice[0].Test", "TestPartial.SubSlice[0].Test", "Test", "Test", "required")
  686. AssertError(t, errs, "TestPartial.SubSlice[1].Test", "TestPartial.SubSlice[1].Test", "Test", "Test", "required")
  687. errs = validate.StructPartial(tPartial, p2...)
  688. NotEqual(t, errs, nil)
  689. Equal(t, len(errs.(ValidationErrors)), 1)
  690. AssertError(t, errs, "TestPartial.SubSlice[0].Test", "TestPartial.SubSlice[0].Test", "Test", "Test", "required")
  691. // reset struct in slice, and unset struct in slice in unset posistion
  692. tPartial.SubSlice[0].Test = "Required"
  693. // these will pass as the unset item is NOT tested
  694. errs = validate.StructPartial(tPartial, p1...)
  695. Equal(t, errs, nil)
  696. errs = validate.StructPartial(tPartial, p2...)
  697. Equal(t, errs, nil)
  698. // testing for missing item by exception, yes it dives and fails
  699. errs = validate.StructExcept(tPartial, p1...)
  700. NotEqual(t, errs, nil)
  701. Equal(t, len(errs.(ValidationErrors)), 1)
  702. AssertError(t, errs, "TestPartial.SubSlice[1].Test", "TestPartial.SubSlice[1].Test", "Test", "Test", "required")
  703. errs = validate.StructExcept(tPartial, p2...)
  704. NotEqual(t, errs, nil)
  705. AssertError(t, errs, "TestPartial.SubSlice[1].Test", "TestPartial.SubSlice[1].Test", "Test", "Test", "required")
  706. tPartial.SubSlice[1].Test = "Required"
  707. tPartial.Anonymous.SubAnonStruct[0].Test = ""
  708. // these will pass as the unset item is NOT tested
  709. errs = validate.StructPartial(tPartial, p1...)
  710. Equal(t, errs, nil)
  711. errs = validate.StructPartial(tPartial, p2...)
  712. Equal(t, errs, nil)
  713. errs = validate.StructExcept(tPartial, p1...)
  714. NotEqual(t, errs, nil)
  715. AssertError(t, errs, "TestPartial.Anonymous.SubAnonStruct[0].Test", "TestPartial.Anonymous.SubAnonStruct[0].Test", "Test", "Test", "required")
  716. errs = validate.StructExcept(tPartial, p2...)
  717. NotEqual(t, errs, nil)
  718. AssertError(t, errs, "TestPartial.Anonymous.SubAnonStruct[0].Test", "TestPartial.Anonymous.SubAnonStruct[0].Test", "Test", "Test", "required")
  719. }
  720. func TestCrossStructLteFieldValidation(t *testing.T) {
  721. type Inner struct {
  722. CreatedAt *time.Time
  723. String string
  724. Int int
  725. Uint uint
  726. Float float64
  727. Array []string
  728. }
  729. type Test struct {
  730. Inner *Inner
  731. CreatedAt *time.Time `validate:"ltecsfield=Inner.CreatedAt"`
  732. String string `validate:"ltecsfield=Inner.String"`
  733. Int int `validate:"ltecsfield=Inner.Int"`
  734. Uint uint `validate:"ltecsfield=Inner.Uint"`
  735. Float float64 `validate:"ltecsfield=Inner.Float"`
  736. Array []string `validate:"ltecsfield=Inner.Array"`
  737. }
  738. now := time.Now().UTC()
  739. then := now.Add(time.Hour * 5)
  740. inner := &Inner{
  741. CreatedAt: &then,
  742. String: "abcd",
  743. Int: 13,
  744. Uint: 13,
  745. Float: 1.13,
  746. Array: []string{"val1", "val2"},
  747. }
  748. test := &Test{
  749. Inner: inner,
  750. CreatedAt: &now,
  751. String: "abc",
  752. Int: 12,
  753. Uint: 12,
  754. Float: 1.12,
  755. Array: []string{"val1"},
  756. }
  757. validate := New()
  758. errs := validate.Struct(test)
  759. Equal(t, errs, nil)
  760. test.CreatedAt = &then
  761. test.String = "abcd"
  762. test.Int = 13
  763. test.Uint = 13
  764. test.Float = 1.13
  765. test.Array = []string{"val1", "val2"}
  766. errs = validate.Struct(test)
  767. Equal(t, errs, nil)
  768. after := now.Add(time.Hour * 10)
  769. test.CreatedAt = &after
  770. test.String = "abce"
  771. test.Int = 14
  772. test.Uint = 14
  773. test.Float = 1.14
  774. test.Array = []string{"val1", "val2", "val3"}
  775. errs = validate.Struct(test)
  776. NotEqual(t, errs, nil)
  777. AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "ltecsfield")
  778. AssertError(t, errs, "Test.String", "Test.String", "String", "String", "ltecsfield")
  779. AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "ltecsfield")
  780. AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "ltecsfield")
  781. AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "ltecsfield")
  782. AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "ltecsfield")
  783. errs = validate.VarWithValueCtx(context.Background(), 1, "", "ltecsfield")
  784. NotEqual(t, errs, nil)
  785. AssertError(t, errs, "", "", "", "", "ltecsfield")
  786. // this test is for the WARNING about unforeseen validation issues.
  787. errs = validate.VarWithValue(test, now, "ltecsfield")
  788. NotEqual(t, errs, nil)
  789. Equal(t, len(errs.(ValidationErrors)), 6)
  790. AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "ltecsfield")
  791. AssertError(t, errs, "Test.String", "Test.String", "String", "String", "ltecsfield")
  792. AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "ltecsfield")
  793. AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "ltecsfield")
  794. AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "ltecsfield")
  795. AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "ltecsfield")
  796. type Other struct {
  797. Value string
  798. }
  799. type Test2 struct {
  800. Value Other
  801. Time time.Time `validate:"ltecsfield=Value"`
  802. }
  803. tst := Test2{
  804. Value: Other{Value: "StringVal"},
  805. Time: then,
  806. }
  807. errs = validate.Struct(tst)
  808. NotEqual(t, errs, nil)
  809. AssertError(t, errs, "Test2.Time", "Test2.Time", "Time", "Time", "ltecsfield")
  810. }
  811. func TestCrossStructLtFieldValidation(t *testing.T) {
  812. type Inner struct {
  813. CreatedAt *time.Time
  814. String string
  815. Int int
  816. Uint uint
  817. Float float64
  818. Array []string
  819. }
  820. type Test struct {
  821. Inner *Inner
  822. CreatedAt *time.Time `validate:"ltcsfield=Inner.CreatedAt"`
  823. String string `validate:"ltcsfield=Inner.String"`
  824. Int int `validate:"ltcsfield=Inner.Int"`
  825. Uint uint `validate:"ltcsfield=Inner.Uint"`
  826. Float float64 `validate:"ltcsfield=Inner.Float"`
  827. Array []string `validate:"ltcsfield=Inner.Array"`
  828. }
  829. now := time.Now().UTC()
  830. then := now.Add(time.Hour * 5)
  831. inner := &Inner{
  832. CreatedAt: &then,
  833. String: "abcd",
  834. Int: 13,
  835. Uint: 13,
  836. Float: 1.13,
  837. Array: []string{"val1", "val2"},
  838. }
  839. test := &Test{
  840. Inner: inner,
  841. CreatedAt: &now,
  842. String: "abc",
  843. Int: 12,
  844. Uint: 12,
  845. Float: 1.12,
  846. Array: []string{"val1"},
  847. }
  848. validate := New()
  849. errs := validate.Struct(test)
  850. Equal(t, errs, nil)
  851. test.CreatedAt = &then
  852. test.String = "abcd"
  853. test.Int = 13
  854. test.Uint = 13
  855. test.Float = 1.13
  856. test.Array = []string{"val1", "val2"}
  857. errs = validate.Struct(test)
  858. NotEqual(t, errs, nil)
  859. AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "ltcsfield")
  860. AssertError(t, errs, "Test.String", "Test.String", "String", "String", "ltcsfield")
  861. AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "ltcsfield")
  862. AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "ltcsfield")
  863. AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "ltcsfield")
  864. AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "ltcsfield")
  865. errs = validate.VarWithValue(1, "", "ltcsfield")
  866. NotEqual(t, errs, nil)
  867. AssertError(t, errs, "", "", "", "", "ltcsfield")
  868. // this test is for the WARNING about unforeseen validation issues.
  869. errs = validate.VarWithValue(test, now, "ltcsfield")
  870. NotEqual(t, errs, nil)
  871. AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "ltcsfield")
  872. AssertError(t, errs, "Test.String", "Test.String", "String", "String", "ltcsfield")
  873. AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "ltcsfield")
  874. AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "ltcsfield")
  875. AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "ltcsfield")
  876. AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "ltcsfield")
  877. type Other struct {
  878. Value string
  879. }
  880. type Test2 struct {
  881. Value Other
  882. Time time.Time `validate:"ltcsfield=Value"`
  883. }
  884. tst := Test2{
  885. Value: Other{Value: "StringVal"},
  886. Time: then,
  887. }
  888. errs = validate.Struct(tst)
  889. NotEqual(t, errs, nil)
  890. AssertError(t, errs, "Test2.Time", "Test2.Time", "Time", "Time", "ltcsfield")
  891. }
  892. func TestCrossStructGteFieldValidation(t *testing.T) {
  893. type Inner struct {
  894. CreatedAt *time.Time
  895. String string
  896. Int int
  897. Uint uint
  898. Float float64
  899. Array []string
  900. }
  901. type Test struct {
  902. Inner *Inner
  903. CreatedAt *time.Time `validate:"gtecsfield=Inner.CreatedAt"`
  904. String string `validate:"gtecsfield=Inner.String"`
  905. Int int `validate:"gtecsfield=Inner.Int"`
  906. Uint uint `validate:"gtecsfield=Inner.Uint"`
  907. Float float64 `validate:"gtecsfield=Inner.Float"`
  908. Array []string `validate:"gtecsfield=Inner.Array"`
  909. }
  910. now := time.Now().UTC()
  911. then := now.Add(time.Hour * -5)
  912. inner := &Inner{
  913. CreatedAt: &then,
  914. String: "abcd",
  915. Int: 13,
  916. Uint: 13,
  917. Float: 1.13,
  918. Array: []string{"val1", "val2"},
  919. }
  920. test := &Test{
  921. Inner: inner,
  922. CreatedAt: &now,
  923. String: "abcde",
  924. Int: 14,
  925. Uint: 14,
  926. Float: 1.14,
  927. Array: []string{"val1", "val2", "val3"},
  928. }
  929. validate := New()
  930. errs := validate.Struct(test)
  931. Equal(t, errs, nil)
  932. test.CreatedAt = &then
  933. test.String = "abcd"
  934. test.Int = 13
  935. test.Uint = 13
  936. test.Float = 1.13
  937. test.Array = []string{"val1", "val2"}
  938. errs = validate.Struct(test)
  939. Equal(t, errs, nil)
  940. before := now.Add(time.Hour * -10)
  941. test.CreatedAt = &before
  942. test.String = "abc"
  943. test.Int = 12
  944. test.Uint = 12
  945. test.Float = 1.12
  946. test.Array = []string{"val1"}
  947. errs = validate.Struct(test)
  948. NotEqual(t, errs, nil)
  949. AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "gtecsfield")
  950. AssertError(t, errs, "Test.String", "Test.String", "String", "String", "gtecsfield")
  951. AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "gtecsfield")
  952. AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "gtecsfield")
  953. AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "gtecsfield")
  954. AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "gtecsfield")
  955. errs = validate.VarWithValue(1, "", "gtecsfield")
  956. NotEqual(t, errs, nil)
  957. AssertError(t, errs, "", "", "", "", "gtecsfield")
  958. // this test is for the WARNING about unforeseen validation issues.
  959. errs = validate.VarWithValue(test, now, "gtecsfield")
  960. NotEqual(t, errs, nil)
  961. AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "gtecsfield")
  962. AssertError(t, errs, "Test.String", "Test.String", "String", "String", "gtecsfield")
  963. AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "gtecsfield")
  964. AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "gtecsfield")
  965. AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "gtecsfield")
  966. AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "gtecsfield")
  967. type Other struct {
  968. Value string
  969. }
  970. type Test2 struct {
  971. Value Other
  972. Time time.Time `validate:"gtecsfield=Value"`
  973. }
  974. tst := Test2{
  975. Value: Other{Value: "StringVal"},
  976. Time: then,
  977. }
  978. errs = validate.Struct(tst)
  979. NotEqual(t, errs, nil)
  980. AssertError(t, errs, "Test2.Time", "Test2.Time", "Time", "Time", "gtecsfield")
  981. }
  982. func TestCrossStructGtFieldValidation(t *testing.T) {
  983. type Inner struct {
  984. CreatedAt *time.Time
  985. String string
  986. Int int
  987. Uint uint
  988. Float float64
  989. Array []string
  990. }
  991. type Test struct {
  992. Inner *Inner
  993. CreatedAt *time.Time `validate:"gtcsfield=Inner.CreatedAt"`
  994. String string `validate:"gtcsfield=Inner.String"`
  995. Int int `validate:"gtcsfield=Inner.Int"`
  996. Uint uint `validate:"gtcsfield=Inner.Uint"`
  997. Float float64 `validate:"gtcsfield=Inner.Float"`
  998. Array []string `validate:"gtcsfield=Inner.Array"`
  999. }
  1000. now := time.Now().UTC()
  1001. then := now.Add(time.Hour * -5)
  1002. inner := &Inner{
  1003. CreatedAt: &then,
  1004. String: "abcd",
  1005. Int: 13,
  1006. Uint: 13,
  1007. Float: 1.13,
  1008. Array: []string{"val1", "val2"},
  1009. }
  1010. test := &Test{
  1011. Inner: inner,
  1012. CreatedAt: &now,
  1013. String: "abcde",
  1014. Int: 14,
  1015. Uint: 14,
  1016. Float: 1.14,
  1017. Array: []string{"val1", "val2", "val3"},
  1018. }
  1019. validate := New()
  1020. errs := validate.Struct(test)
  1021. Equal(t, errs, nil)
  1022. test.CreatedAt = &then
  1023. test.String = "abcd"
  1024. test.Int = 13
  1025. test.Uint = 13
  1026. test.Float = 1.13
  1027. test.Array = []string{"val1", "val2"}
  1028. errs = validate.Struct(test)
  1029. NotEqual(t, errs, nil)
  1030. AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "gtcsfield")
  1031. AssertError(t, errs, "Test.String", "Test.String", "String", "String", "gtcsfield")
  1032. AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "gtcsfield")
  1033. AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "gtcsfield")
  1034. AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "gtcsfield")
  1035. AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "gtcsfield")
  1036. errs = validate.VarWithValue(1, "", "gtcsfield")
  1037. NotEqual(t, errs, nil)
  1038. AssertError(t, errs, "", "", "", "", "gtcsfield")
  1039. // this test is for the WARNING about unforeseen validation issues.
  1040. errs = validate.VarWithValue(test, now, "gtcsfield")
  1041. NotEqual(t, errs, nil)
  1042. AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "gtcsfield")
  1043. AssertError(t, errs, "Test.String", "Test.String", "String", "String", "gtcsfield")
  1044. AssertError(t, errs, "Test.Int", "Test.Int", "Int", "Int", "gtcsfield")
  1045. AssertError(t, errs, "Test.Uint", "Test.Uint", "Uint", "Uint", "gtcsfield")
  1046. AssertError(t, errs, "Test.Float", "Test.Float", "Float", "Float", "gtcsfield")
  1047. AssertError(t, errs, "Test.Array", "Test.Array", "Array", "Array", "gtcsfield")
  1048. type Other struct {
  1049. Value string
  1050. }
  1051. type Test2 struct {
  1052. Value Other
  1053. Time time.Time `validate:"gtcsfield=Value"`
  1054. }
  1055. tst := Test2{
  1056. Value: Other{Value: "StringVal"},
  1057. Time: then,
  1058. }
  1059. errs = validate.Struct(tst)
  1060. NotEqual(t, errs, nil)
  1061. AssertError(t, errs, "Test2.Time", "Test2.Time", "Time", "Time", "gtcsfield")
  1062. }
  1063. func TestCrossStructNeFieldValidation(t *testing.T) {
  1064. type Inner struct {
  1065. CreatedAt *time.Time
  1066. }
  1067. type Test struct {
  1068. Inner *Inner
  1069. CreatedAt *time.Time `validate:"necsfield=Inner.CreatedAt"`
  1070. }
  1071. now := time.Now().UTC()
  1072. then := now.Add(time.Hour * 5)
  1073. inner := &Inner{
  1074. CreatedAt: &then,
  1075. }
  1076. test := &Test{
  1077. Inner: inner,
  1078. CreatedAt: &now,
  1079. }
  1080. validate := New()
  1081. errs := validate.Struct(test)
  1082. Equal(t, errs, nil)
  1083. test.CreatedAt = &then
  1084. errs = validate.Struct(test)
  1085. NotEqual(t, errs, nil)
  1086. AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "necsfield")
  1087. var j uint64
  1088. var k float64
  1089. var j2 uint64
  1090. var k2 float64
  1091. s := "abcd"
  1092. i := 1
  1093. j = 1
  1094. k = 1.543
  1095. arr := []string{"test"}
  1096. s2 := "abcd"
  1097. i2 := 1
  1098. j2 = 1
  1099. k2 = 1.543
  1100. arr2 := []string{"test"}
  1101. arr3 := []string{"test", "test2"}
  1102. now2 := now
  1103. errs = validate.VarWithValue(s, s2, "necsfield")
  1104. NotEqual(t, errs, nil)
  1105. AssertError(t, errs, "", "", "", "", "necsfield")
  1106. errs = validate.VarWithValue(i2, i, "necsfield")
  1107. NotEqual(t, errs, nil)
  1108. AssertError(t, errs, "", "", "", "", "necsfield")
  1109. errs = validate.VarWithValue(j2, j, "necsfield")
  1110. NotEqual(t, errs, nil)
  1111. AssertError(t, errs, "", "", "", "", "necsfield")
  1112. errs = validate.VarWithValue(k2, k, "necsfield")
  1113. NotEqual(t, errs, nil)
  1114. AssertError(t, errs, "", "", "", "", "necsfield")
  1115. errs = validate.VarWithValue(arr2, arr, "necsfield")
  1116. NotEqual(t, errs, nil)
  1117. AssertError(t, errs, "", "", "", "", "necsfield")
  1118. errs = validate.VarWithValue(now2, now, "necsfield")
  1119. NotEqual(t, errs, nil)
  1120. AssertError(t, errs, "", "", "", "", "necsfield")
  1121. errs = validate.VarWithValue(arr3, arr, "necsfield")
  1122. Equal(t, errs, nil)
  1123. type SInner struct {
  1124. Name string
  1125. }
  1126. type TStruct struct {
  1127. Inner *SInner
  1128. CreatedAt *time.Time `validate:"necsfield=Inner"`
  1129. }
  1130. sinner := &SInner{
  1131. Name: "NAME",
  1132. }
  1133. test2 := &TStruct{
  1134. Inner: sinner,
  1135. CreatedAt: &now,
  1136. }
  1137. errs = validate.Struct(test2)
  1138. Equal(t, errs, nil)
  1139. test2.Inner = nil
  1140. errs = validate.Struct(test2)
  1141. Equal(t, errs, nil)
  1142. errs = validate.VarWithValue(nil, 1, "necsfield")
  1143. NotEqual(t, errs, nil)
  1144. AssertError(t, errs, "", "", "", "", "necsfield")
  1145. }
  1146. func TestCrossStructEqFieldValidation(t *testing.T) {
  1147. type Inner struct {
  1148. CreatedAt *time.Time
  1149. }
  1150. type Test struct {
  1151. Inner *Inner
  1152. CreatedAt *time.Time `validate:"eqcsfield=Inner.CreatedAt"`
  1153. }
  1154. now := time.Now().UTC()
  1155. inner := &Inner{
  1156. CreatedAt: &now,
  1157. }
  1158. test := &Test{
  1159. Inner: inner,
  1160. CreatedAt: &now,
  1161. }
  1162. validate := New()
  1163. errs := validate.Struct(test)
  1164. Equal(t, errs, nil)
  1165. newTime := time.Now().UTC()
  1166. test.CreatedAt = &newTime
  1167. errs = validate.Struct(test)
  1168. NotEqual(t, errs, nil)
  1169. AssertError(t, errs, "Test.CreatedAt", "Test.CreatedAt", "CreatedAt", "CreatedAt", "eqcsfield")
  1170. var j uint64
  1171. var k float64
  1172. s := "abcd"
  1173. i := 1
  1174. j = 1
  1175. k = 1.543
  1176. arr := []string{"test"}
  1177. var j2 uint64
  1178. var k2 float64
  1179. s2 := "abcd"
  1180. i2 := 1
  1181. j2 = 1
  1182. k2 = 1.543
  1183. arr2 := []string{"test"}
  1184. arr3 := []string{"test", "test2"}
  1185. now2 := now
  1186. errs = validate.VarWithValue(s, s2, "eqcsfield")
  1187. Equal(t, errs, nil)
  1188. errs = validate.VarWithValue(i2, i, "eqcsfield")
  1189. Equal(t, errs, nil)
  1190. errs = validate.VarWithValue(j2, j, "eqcsfield")
  1191. Equal(t, errs, nil)
  1192. errs = validate.VarWithValue(k2, k, "eqcsfield")
  1193. Equal(t, errs, nil)
  1194. errs = validate.VarWithValue(arr2, arr, "eqcsfield")
  1195. Equal(t, errs, nil)
  1196. errs = validate.VarWithValue(now2, now, "eqcsfield")
  1197. Equal(t, errs, nil)
  1198. errs = validate.VarWithValue(arr3, arr, "eqcsfield")
  1199. NotEqual(t, errs, nil)
  1200. AssertError(t, errs, "", "", "", "", "eqcsfield")
  1201. type SInner struct {
  1202. Name string
  1203. }
  1204. type TStruct struct {
  1205. Inner *SInner
  1206. CreatedAt *time.Time `validate:"eqcsfield=Inner"`
  1207. }
  1208. sinner := &SInner{
  1209. Name: "NAME",
  1210. }
  1211. test2 := &TStruct{
  1212. Inner: sinner,
  1213. CreatedAt: &now,
  1214. }
  1215. errs = validate.Struct(test2)
  1216. NotEqual(t, errs, nil)
  1217. AssertError(t, errs, "TStruct.CreatedAt", "TStruct.CreatedAt", "CreatedAt", "CreatedAt", "eqcsfield")
  1218. test2.Inner = nil
  1219. errs = validate.Struct(test2)
  1220. NotEqual(t, errs, nil)
  1221. AssertError(t, errs, "TStruct.CreatedAt", "TStruct.CreatedAt", "CreatedAt", "CreatedAt", "eqcsfield")
  1222. errs = validate.VarWithValue(nil, 1, "eqcsfield")
  1223. NotEqual(t, errs, nil)
  1224. AssertError(t, errs, "", "", "", "", "eqcsfield")
  1225. }
  1226. func TestCrossNamespaceFieldValidation(t *testing.T) {
  1227. type SliceStruct struct {
  1228. Name string
  1229. }
  1230. type Inner struct {
  1231. CreatedAt *time.Time
  1232. Slice []string
  1233. SliceStructs []*SliceStruct
  1234. SliceSlice [][]string
  1235. SliceSliceStruct [][]*SliceStruct
  1236. SliceMap []map[string]string
  1237. Map map[string]string
  1238. MapMap map[string]map[string]string
  1239. MapStructs map[string]*SliceStruct
  1240. MapMapStruct map[string]map[string]*SliceStruct
  1241. MapSlice map[string][]string
  1242. MapInt map[int]string
  1243. MapInt8 map[int8]string
  1244. MapInt16 map[int16]string
  1245. MapInt32 map[int32]string
  1246. MapInt64 map[int64]string
  1247. MapUint map[uint]string
  1248. MapUint8 map[uint8]string
  1249. MapUint16 map[uint16]string
  1250. MapUint32 map[uint32]string
  1251. MapUint64 map[uint64]string
  1252. MapFloat32 map[float32]string
  1253. MapFloat64 map[float64]string
  1254. MapBool map[bool]string
  1255. }
  1256. type Test struct {
  1257. Inner *Inner
  1258. CreatedAt *time.Time
  1259. }
  1260. now := time.Now()
  1261. inner := &Inner{
  1262. CreatedAt: &now,
  1263. Slice: []string{"val1", "val2", "val3"},
  1264. SliceStructs: []*SliceStruct{{Name: "name1"}, {Name: "name2"}, {Name: "name3"}},
  1265. SliceSlice: [][]string{{"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}},
  1266. SliceSliceStruct: [][]*SliceStruct{{{Name: "name1"}, {Name: "name2"}, {Name: "name3"}}, {{Name: "name4"}, {Name: "name5"}, {Name: "name6"}}, {{Name: "name7"}, {Name: "name8"}, {Name: "name9"}}},
  1267. SliceMap: []map[string]string{{"key1": "val1", "key2": "val2", "key3": "val3"}, {"key4": "val4", "key5": "val5", "key6": "val6"}},
  1268. Map: map[string]string{"key1": "val1", "key2": "val2", "key3": "val3"},
  1269. MapStructs: map[string]*SliceStruct{"key1": {Name: "name1"}, "key2": {Name: "name2"}, "key3": {Name: "name3"}},
  1270. MapMap: map[string]map[string]string{"key1": {"key1-1": "val1"}, "key2": {"key2-1": "val2"}, "key3": {"key3-1": "val3"}},
  1271. MapMapStruct: map[string]map[string]*SliceStruct{"key1": {"key1-1": {Name: "name1"}}, "key2": {"key2-1": {Name: "name2"}}, "key3": {"key3-1": {Name: "name3"}}},
  1272. MapSlice: map[string][]string{"key1": {"1", "2", "3"}, "key2": {"4", "5", "6"}, "key3": {"7", "8", "9"}},
  1273. MapInt: map[int]string{1: "val1", 2: "val2", 3: "val3"},
  1274. MapInt8: map[int8]string{1: "val1", 2: "val2", 3: "val3"},
  1275. MapInt16: map[int16]string{1: "val1", 2: "val2", 3: "val3"},
  1276. MapInt32: map[int32]string{1: "val1", 2: "val2", 3: "val3"},
  1277. MapInt64: map[int64]string{1: "val1", 2: "val2", 3: "val3"},
  1278. MapUint: map[uint]string{1: "val1", 2: "val2", 3: "val3"},
  1279. MapUint8: map[uint8]string{1: "val1", 2: "val2", 3: "val3"},
  1280. MapUint16: map[uint16]string{1: "val1", 2: "val2", 3: "val3"},
  1281. MapUint32: map[uint32]string{1: "val1", 2: "val2", 3: "val3"},
  1282. MapUint64: map[uint64]string{1: "val1", 2: "val2", 3: "val3"},
  1283. MapFloat32: map[float32]string{1.01: "val1", 2.02: "val2", 3.03: "val3"},
  1284. MapFloat64: map[float64]string{1.01: "val1", 2.02: "val2", 3.03: "val3"},
  1285. MapBool: map[bool]string{true: "val1", false: "val2"},
  1286. }
  1287. test := &Test{
  1288. Inner: inner,
  1289. CreatedAt: &now,
  1290. }
  1291. val := reflect.ValueOf(test)
  1292. vd := New()
  1293. v := &validate{
  1294. v: vd,
  1295. }
  1296. current, kind, ok := v.getStructFieldOKInternal(val, "Inner.CreatedAt")
  1297. Equal(t, ok, true)
  1298. Equal(t, kind, reflect.Struct)
  1299. tm, ok := current.Interface().(time.Time)
  1300. Equal(t, ok, true)
  1301. Equal(t, tm, now)
  1302. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.Slice[1]")
  1303. Equal(t, ok, true)
  1304. Equal(t, kind, reflect.String)
  1305. Equal(t, current.String(), "val2")
  1306. current, _, ok = v.getStructFieldOKInternal(val, "Inner.CrazyNonExistantField")
  1307. Equal(t, ok, false)
  1308. current, _, ok = v.getStructFieldOKInternal(val, "Inner.Slice[101]")
  1309. Equal(t, ok, false)
  1310. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.Map[key3]")
  1311. Equal(t, ok, true)
  1312. Equal(t, kind, reflect.String)
  1313. Equal(t, current.String(), "val3")
  1314. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapMap[key2][key2-1]")
  1315. Equal(t, ok, true)
  1316. Equal(t, kind, reflect.String)
  1317. Equal(t, current.String(), "val2")
  1318. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapStructs[key2].Name")
  1319. Equal(t, ok, true)
  1320. Equal(t, kind, reflect.String)
  1321. Equal(t, current.String(), "name2")
  1322. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapMapStruct[key3][key3-1].Name")
  1323. Equal(t, ok, true)
  1324. Equal(t, kind, reflect.String)
  1325. Equal(t, current.String(), "name3")
  1326. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.SliceSlice[2][0]")
  1327. Equal(t, ok, true)
  1328. Equal(t, kind, reflect.String)
  1329. Equal(t, current.String(), "7")
  1330. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.SliceSliceStruct[2][1].Name")
  1331. Equal(t, ok, true)
  1332. Equal(t, kind, reflect.String)
  1333. Equal(t, current.String(), "name8")
  1334. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.SliceMap[1][key5]")
  1335. Equal(t, ok, true)
  1336. Equal(t, kind, reflect.String)
  1337. Equal(t, current.String(), "val5")
  1338. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapSlice[key3][2]")
  1339. Equal(t, ok, true)
  1340. Equal(t, kind, reflect.String)
  1341. Equal(t, current.String(), "9")
  1342. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapInt[2]")
  1343. Equal(t, ok, true)
  1344. Equal(t, kind, reflect.String)
  1345. Equal(t, current.String(), "val2")
  1346. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapInt8[2]")
  1347. Equal(t, ok, true)
  1348. Equal(t, kind, reflect.String)
  1349. Equal(t, current.String(), "val2")
  1350. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapInt16[2]")
  1351. Equal(t, ok, true)
  1352. Equal(t, kind, reflect.String)
  1353. Equal(t, current.String(), "val2")
  1354. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapInt32[2]")
  1355. Equal(t, ok, true)
  1356. Equal(t, kind, reflect.String)
  1357. Equal(t, current.String(), "val2")
  1358. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapInt64[2]")
  1359. Equal(t, ok, true)
  1360. Equal(t, kind, reflect.String)
  1361. Equal(t, current.String(), "val2")
  1362. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapUint[2]")
  1363. Equal(t, ok, true)
  1364. Equal(t, kind, reflect.String)
  1365. Equal(t, current.String(), "val2")
  1366. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapUint8[2]")
  1367. Equal(t, ok, true)
  1368. Equal(t, kind, reflect.String)
  1369. Equal(t, current.String(), "val2")
  1370. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapUint16[2]")
  1371. Equal(t, ok, true)
  1372. Equal(t, kind, reflect.String)
  1373. Equal(t, current.String(), "val2")
  1374. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapUint32[2]")
  1375. Equal(t, ok, true)
  1376. Equal(t, kind, reflect.String)
  1377. Equal(t, current.String(), "val2")
  1378. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapUint64[2]")
  1379. Equal(t, ok, true)
  1380. Equal(t, kind, reflect.String)
  1381. Equal(t, current.String(), "val2")
  1382. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapFloat32[3.03]")
  1383. Equal(t, ok, true)
  1384. Equal(t, kind, reflect.String)
  1385. Equal(t, current.String(), "val3")
  1386. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapFloat64[2.02]")
  1387. Equal(t, ok, true)
  1388. Equal(t, kind, reflect.String)
  1389. Equal(t, current.String(), "val2")
  1390. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.MapBool[true]")
  1391. Equal(t, ok, true)
  1392. Equal(t, kind, reflect.String)
  1393. Equal(t, current.String(), "val1")
  1394. inner = &Inner{
  1395. CreatedAt: &now,
  1396. Slice: []string{"val1", "val2", "val3"},
  1397. SliceStructs: []*SliceStruct{{Name: "name1"}, {Name: "name2"}, nil},
  1398. SliceSlice: [][]string{{"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}},
  1399. SliceSliceStruct: [][]*SliceStruct{{{Name: "name1"}, {Name: "name2"}, {Name: "name3"}}, {{Name: "name4"}, {Name: "name5"}, {Name: "name6"}}, {{Name: "name7"}, {Name: "name8"}, {Name: "name9"}}},
  1400. SliceMap: []map[string]string{{"key1": "val1", "key2": "val2", "key3": "val3"}, {"key4": "val4", "key5": "val5", "key6": "val6"}},
  1401. Map: map[string]string{"key1": "val1", "key2": "val2", "key3": "val3"},
  1402. MapStructs: map[string]*SliceStruct{"key1": {Name: "name1"}, "key2": {Name: "name2"}, "key3": {Name: "name3"}},
  1403. MapMap: map[string]map[string]string{"key1": {"key1-1": "val1"}, "key2": {"key2-1": "val2"}, "key3": {"key3-1": "val3"}},
  1404. MapMapStruct: map[string]map[string]*SliceStruct{"key1": {"key1-1": {Name: "name1"}}, "key2": {"key2-1": {Name: "name2"}}, "key3": {"key3-1": {Name: "name3"}}},
  1405. MapSlice: map[string][]string{"key1": {"1", "2", "3"}, "key2": {"4", "5", "6"}, "key3": {"7", "8", "9"}},
  1406. }
  1407. test = &Test{
  1408. Inner: inner,
  1409. CreatedAt: nil,
  1410. }
  1411. val = reflect.ValueOf(test)
  1412. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.SliceStructs[2]")
  1413. Equal(t, ok, true)
  1414. Equal(t, kind, reflect.Ptr)
  1415. Equal(t, current.String(), "<*validator.SliceStruct Value>")
  1416. Equal(t, current.IsNil(), true)
  1417. current, kind, ok = v.getStructFieldOKInternal(val, "Inner.SliceStructs[2].Name")
  1418. Equal(t, ok, false)
  1419. Equal(t, kind, reflect.Ptr)
  1420. Equal(t, current.String(), "<*validator.SliceStruct Value>")
  1421. Equal(t, current.IsNil(), true)
  1422. PanicMatches(t, func() { v.getStructFieldOKInternal(reflect.ValueOf(1), "crazyinput") }, "Invalid field namespace")
  1423. }
  1424. func TestExistsValidation(t *testing.T) {
  1425. jsonText := "{ \"truthiness2\": true }"
  1426. type Thing struct {
  1427. Truthiness *bool `json:"truthiness" validate:"required"`
  1428. }
  1429. var ting Thing
  1430. err := json.Unmarshal([]byte(jsonText), &ting)
  1431. Equal(t, err, nil)
  1432. NotEqual(t, ting, nil)
  1433. Equal(t, ting.Truthiness, nil)
  1434. validate := New()
  1435. errs := validate.Struct(ting)
  1436. NotEqual(t, errs, nil)
  1437. AssertError(t, errs, "Thing.Truthiness", "Thing.Truthiness", "Truthiness", "Truthiness", "required")
  1438. jsonText = "{ \"truthiness\": true }"
  1439. err = json.Unmarshal([]byte(jsonText), &ting)
  1440. Equal(t, err, nil)
  1441. NotEqual(t, ting, nil)
  1442. Equal(t, ting.Truthiness, true)
  1443. errs = validate.Struct(ting)
  1444. Equal(t, errs, nil)
  1445. }
  1446. func TestSQLValue2Validation(t *testing.T) {
  1447. validate := New()
  1448. validate.RegisterCustomTypeFunc(ValidateValuerType, valuer{}, (*driver.Valuer)(nil), sql.NullString{}, sql.NullInt64{}, sql.NullBool{}, sql.NullFloat64{})
  1449. validate.RegisterCustomTypeFunc(ValidateCustomType, MadeUpCustomType{})
  1450. validate.RegisterCustomTypeFunc(OverrideIntTypeForSomeReason, 1)
  1451. val := valuer{
  1452. Name: "",
  1453. }
  1454. errs := validate.Var(val, "required")
  1455. NotEqual(t, errs, nil)
  1456. AssertError(t, errs, "", "", "", "", "required")
  1457. val.Name = "Valid Name"
  1458. errs = validate.VarCtx(context.Background(), val, "required")
  1459. Equal(t, errs, nil)
  1460. val.Name = "errorme"
  1461. PanicMatches(t, func() { validate.Var(val, "required") }, "SQL Driver Valuer error: some kind of error")
  1462. myVal := valuer{
  1463. Name: "",
  1464. }
  1465. errs = validate.Var(myVal, "required")
  1466. NotEqual(t, errs, nil)
  1467. AssertError(t, errs, "", "", "", "", "required")
  1468. cust := MadeUpCustomType{
  1469. FirstName: "Joey",
  1470. LastName: "Bloggs",
  1471. }
  1472. c := CustomMadeUpStruct{MadeUp: cust, OverriddenInt: 2}
  1473. errs = validate.Struct(c)
  1474. Equal(t, errs, nil)
  1475. c.MadeUp.FirstName = ""
  1476. c.OverriddenInt = 1
  1477. errs = validate.Struct(c)
  1478. NotEqual(t, errs, nil)
  1479. Equal(t, len(errs.(ValidationErrors)), 2)
  1480. AssertError(t, errs, "CustomMadeUpStruct.MadeUp", "CustomMadeUpStruct.MadeUp", "MadeUp", "MadeUp", "required")
  1481. AssertError(t, errs, "CustomMadeUpStruct.OverriddenInt", "CustomMadeUpStruct.OverriddenInt", "OverriddenInt", "OverriddenInt", "gt")
  1482. }
  1483. func TestSQLValueValidation(t *testing.T) {
  1484. validate := New()
  1485. validate.RegisterCustomTypeFunc(ValidateValuerType, (*driver.Valuer)(nil), valuer{})
  1486. validate.RegisterCustomTypeFunc(ValidateCustomType, MadeUpCustomType{})
  1487. validate.RegisterCustomTypeFunc(OverrideIntTypeForSomeReason, 1)
  1488. val := valuer{
  1489. Name: "",
  1490. }
  1491. errs := validate.Var(val, "required")
  1492. NotEqual(t, errs, nil)
  1493. AssertError(t, errs, "", "", "", "", "required")
  1494. val.Name = "Valid Name"
  1495. errs = validate.Var(val, "required")
  1496. Equal(t, errs, nil)
  1497. val.Name = "errorme"
  1498. PanicMatches(t, func() { errs = validate.Var(val, "required") }, "SQL Driver Valuer error: some kind of error")
  1499. myVal := valuer{
  1500. Name: "",
  1501. }
  1502. errs = validate.Var(myVal, "required")
  1503. NotEqual(t, errs, nil)
  1504. AssertError(t, errs, "", "", "", "", "required")
  1505. cust := MadeUpCustomType{
  1506. FirstName: "Joey",
  1507. LastName: "Bloggs",
  1508. }
  1509. c := CustomMadeUpStruct{MadeUp: cust, OverriddenInt: 2}
  1510. errs = validate.Struct(c)
  1511. Equal(t, errs, nil)
  1512. c.MadeUp.FirstName = ""
  1513. c.OverriddenInt = 1
  1514. errs = validate.Struct(c)
  1515. NotEqual(t, errs, nil)
  1516. Equal(t, len(errs.(ValidationErrors)), 2)
  1517. AssertError(t, errs, "CustomMadeUpStruct.MadeUp", "CustomMadeUpStruct.MadeUp", "MadeUp", "MadeUp", "required")
  1518. AssertError(t, errs, "CustomMadeUpStruct.OverriddenInt", "CustomMadeUpStruct.OverriddenInt", "OverriddenInt", "OverriddenInt", "gt")
  1519. }
  1520. func TestMACValidation(t *testing.T) {
  1521. tests := []struct {
  1522. param string
  1523. expected bool
  1524. }{
  1525. {"3D:F2:C9:A6:B3:4F", true},
  1526. {"3D-F2-C9-A6-B3:4F", false},
  1527. {"123", false},
  1528. {"", false},
  1529. {"abacaba", false},
  1530. {"00:25:96:FF:FE:12:34:56", true},
  1531. {"0025:96FF:FE12:3456", false},
  1532. }
  1533. validate := New()
  1534. for i, test := range tests {
  1535. errs := validate.Var(test.param, "mac")
  1536. if test.expected {
  1537. if !IsEqual(errs, nil) {
  1538. t.Fatalf("Index: %d mac failed Error: %s", i, errs)
  1539. }
  1540. } else {
  1541. if IsEqual(errs, nil) {
  1542. t.Fatalf("Index: %d mac failed Error: %s", i, errs)
  1543. } else {
  1544. val := getError(errs, "", "")
  1545. if val.Tag() != "mac" {
  1546. t.Fatalf("Index: %d mac failed Error: %s", i, errs)
  1547. }
  1548. }
  1549. }
  1550. }
  1551. }
  1552. func TestIPValidation(t *testing.T) {
  1553. tests := []struct {
  1554. param string
  1555. expected bool
  1556. }{
  1557. {"", false},
  1558. {"10.0.0.1", true},
  1559. {"172.16.0.1", true},
  1560. {"192.168.0.1", true},
  1561. {"192.168.255.254", true},
  1562. {"192.168.255.256", false},
  1563. {"172.16.255.254", true},
  1564. {"172.16.256.255", false},
  1565. {"2001:cdba:0000:0000:0000:0000:3257:9652", true},
  1566. {"2001:cdba:0:0:0:0:3257:9652", true},
  1567. {"2001:cdba::3257:9652", true},
  1568. }
  1569. validate := New()
  1570. for i, test := range tests {
  1571. errs := validate.Var(test.param, "ip")
  1572. if test.expected {
  1573. if !IsEqual(errs, nil) {
  1574. t.Fatalf("Index: %d ip failed Error: %s", i, errs)
  1575. }
  1576. } else {
  1577. if IsEqual(errs, nil) {
  1578. t.Fatalf("Index: %d ip failed Error: %s", i, errs)
  1579. } else {
  1580. val := getError(errs, "", "")
  1581. if val.Tag() != "ip" {
  1582. t.Fatalf("Index: %d ip failed Error: %s", i, errs)
  1583. }
  1584. }
  1585. }
  1586. }
  1587. }
  1588. func TestIPv6Validation(t *testing.T) {
  1589. tests := []struct {
  1590. param string
  1591. expected bool
  1592. }{
  1593. {"10.0.0.1", false},
  1594. {"172.16.0.1", false},
  1595. {"192.168.0.1", false},
  1596. {"192.168.255.254", false},
  1597. {"192.168.255.256", false},
  1598. {"172.16.255.254", false},
  1599. {"172.16.256.255", false},
  1600. {"2001:cdba:0000:0000:0000:0000:3257:9652", true},
  1601. {"2001:cdba:0:0:0:0:3257:9652", true},
  1602. {"2001:cdba::3257:9652", true},
  1603. }
  1604. validate := New()
  1605. for i, test := range tests {
  1606. errs := validate.Var(test.param, "ipv6")
  1607. if test.expected {
  1608. if !IsEqual(errs, nil) {
  1609. t.Fatalf("Index: %d ipv6 failed Error: %s", i, errs)
  1610. }
  1611. } else {
  1612. if IsEqual(errs, nil) {
  1613. t.Fatalf("Index: %d ipv6 failed Error: %s", i, errs)
  1614. } else {
  1615. val := getError(errs, "", "")
  1616. if val.Tag() != "ipv6" {
  1617. t.Fatalf("Index: %d ipv6 failed Error: %s", i, errs)
  1618. }
  1619. }
  1620. }
  1621. }
  1622. }
  1623. func TestIPv4Validation(t *testing.T) {
  1624. tests := []struct {
  1625. param string
  1626. expected bool
  1627. }{
  1628. {"10.0.0.1", true},
  1629. {"172.16.0.1", true},
  1630. {"192.168.0.1", true},
  1631. {"192.168.255.254", true},
  1632. {"192.168.255.256", false},
  1633. {"172.16.255.254", true},
  1634. {"172.16.256.255", false},
  1635. {"2001:cdba:0000:0000:0000:0000:3257:9652", false},
  1636. {"2001:cdba:0:0:0:0:3257:9652", false},
  1637. {"2001:cdba::3257:9652", false},
  1638. }
  1639. validate := New()
  1640. for i, test := range tests {
  1641. errs := validate.Var(test.param, "ipv4")
  1642. if test.expected {
  1643. if !IsEqual(errs, nil) {
  1644. t.Fatalf("Index: %d ipv4 failed Error: %s", i, errs)
  1645. }
  1646. } else {
  1647. if IsEqual(errs, nil) {
  1648. t.Fatalf("Index: %d ipv4 failed Error: %s", i, errs)
  1649. } else {
  1650. val := getError(errs, "", "")
  1651. if val.Tag() != "ipv4" {
  1652. t.Fatalf("Index: %d ipv4 failed Error: %s", i, errs)
  1653. }
  1654. }
  1655. }
  1656. }
  1657. }
  1658. func TestCIDRValidation(t *testing.T) {
  1659. tests := []struct {
  1660. param string
  1661. expected bool
  1662. }{
  1663. {"10.0.0.0/0", true},
  1664. {"10.0.0.1/8", true},
  1665. {"172.16.0.1/16", true},
  1666. {"192.168.0.1/24", true},
  1667. {"192.168.255.254/24", true},
  1668. {"192.168.255.254/48", false},
  1669. {"192.168.255.256/24", false},
  1670. {"172.16.255.254/16", true},
  1671. {"172.16.256.255/16", false},
  1672. {"2001:cdba:0000:0000:0000:0000:3257:9652/64", true},
  1673. {"2001:cdba:0000:0000:0000:0000:3257:9652/256", false},
  1674. {"2001:cdba:0:0:0:0:3257:9652/32", true},
  1675. {"2001:cdba::3257:9652/16", true},
  1676. }
  1677. validate := New()
  1678. for i, test := range tests {
  1679. errs := validate.Var(test.param, "cidr")
  1680. if test.expected {
  1681. if !IsEqual(errs, nil) {
  1682. t.Fatalf("Index: %d cidr failed Error: %s", i, errs)
  1683. }
  1684. } else {
  1685. if IsEqual(errs, nil) {
  1686. t.Fatalf("Index: %d cidr failed Error: %s", i, errs)
  1687. } else {
  1688. val := getError(errs, "", "")
  1689. if val.Tag() != "cidr" {
  1690. t.Fatalf("Index: %d cidr failed Error: %s", i, errs)
  1691. }
  1692. }
  1693. }
  1694. }
  1695. }
  1696. func TestCIDRv6Validation(t *testing.T) {
  1697. tests := []struct {
  1698. param string
  1699. expected bool
  1700. }{
  1701. {"10.0.0.0/0", false},
  1702. {"10.0.0.1/8", false},
  1703. {"172.16.0.1/16", false},
  1704. {"192.168.0.1/24", false},
  1705. {"192.168.255.254/24", false},
  1706. {"192.168.255.254/48", false},
  1707. {"192.168.255.256/24", false},
  1708. {"172.16.255.254/16", false},
  1709. {"172.16.256.255/16", false},
  1710. {"2001:cdba:0000:0000:0000:0000:3257:9652/64", true},
  1711. {"2001:cdba:0000:0000:0000:0000:3257:9652/256", false},
  1712. {"2001:cdba:0:0:0:0:3257:9652/32", true},
  1713. {"2001:cdba::3257:9652/16", true},
  1714. }
  1715. validate := New()
  1716. for i, test := range tests {
  1717. errs := validate.Var(test.param, "cidrv6")
  1718. if test.expected {
  1719. if !IsEqual(errs, nil) {
  1720. t.Fatalf("Index: %d cidrv6 failed Error: %s", i, errs)
  1721. }
  1722. } else {
  1723. if IsEqual(errs, nil) {
  1724. t.Fatalf("Index: %d cidrv6 failed Error: %s", i, errs)
  1725. } else {
  1726. val := getError(errs, "", "")
  1727. if val.Tag() != "cidrv6" {
  1728. t.Fatalf("Index: %d cidrv6 failed Error: %s", i, errs)
  1729. }
  1730. }
  1731. }
  1732. }
  1733. }
  1734. func TestCIDRv4Validation(t *testing.T) {
  1735. tests := []struct {
  1736. param string
  1737. expected bool
  1738. }{
  1739. {"10.0.0.0/0", true},
  1740. {"10.0.0.1/8", true},
  1741. {"172.16.0.1/16", true},
  1742. {"192.168.0.1/24", true},
  1743. {"192.168.255.254/24", true},
  1744. {"192.168.255.254/48", false},
  1745. {"192.168.255.256/24", false},
  1746. {"172.16.255.254/16", true},
  1747. {"172.16.256.255/16", false},
  1748. {"2001:cdba:0000:0000:0000:0000:3257:9652/64", false},
  1749. {"2001:cdba:0000:0000:0000:0000:3257:9652/256", false},
  1750. {"2001:cdba:0:0:0:0:3257:9652/32", false},
  1751. {"2001:cdba::3257:9652/16", false},
  1752. }
  1753. validate := New()
  1754. for i, test := range tests {
  1755. errs := validate.Var(test.param, "cidrv4")
  1756. if test.expected {
  1757. if !IsEqual(errs, nil) {
  1758. t.Fatalf("Index: %d cidrv4 failed Error: %s", i, errs)
  1759. }
  1760. } else {
  1761. if IsEqual(errs, nil) {
  1762. t.Fatalf("Index: %d cidrv4 failed Error: %s", i, errs)
  1763. } else {
  1764. val := getError(errs, "", "")
  1765. if val.Tag() != "cidrv4" {
  1766. t.Fatalf("Index: %d cidrv4 failed Error: %s", i, errs)
  1767. }
  1768. }
  1769. }
  1770. }
  1771. }
  1772. func TestTCPAddrValidation(t *testing.T) {
  1773. tests := []struct {
  1774. param string
  1775. expected bool
  1776. }{
  1777. {"", false},
  1778. {":80", false},
  1779. {"127.0.0.1:80", true},
  1780. {"[::1]:80", true},
  1781. {"256.0.0.0:1", false},
  1782. {"[::1]", false},
  1783. }
  1784. validate := New()
  1785. for i, test := range tests {
  1786. errs := validate.Var(test.param, "tcp_addr")
  1787. if test.expected {
  1788. if !IsEqual(errs, nil) {
  1789. t.Fatalf("Index: %d tcp_addr failed Error: %s", i, errs)
  1790. }
  1791. } else {
  1792. if IsEqual(errs, nil) {
  1793. t.Fatalf("Index: %d tcp_addr failed Error: %s", i, errs)
  1794. } else {
  1795. val := getError(errs, "", "")
  1796. if val.Tag() != "tcp_addr" {
  1797. t.Fatalf("Index: %d tcp_addr failed Error: %s", i, errs)
  1798. }
  1799. }
  1800. }
  1801. }
  1802. }
  1803. func TestTCP6AddrValidation(t *testing.T) {
  1804. tests := []struct {
  1805. param string
  1806. expected bool
  1807. }{
  1808. {"", false},
  1809. {":80", false},
  1810. {"127.0.0.1:80", false},
  1811. {"[::1]:80", true},
  1812. {"256.0.0.0:1", false},
  1813. {"[::1]", false},
  1814. }
  1815. validate := New()
  1816. for i, test := range tests {
  1817. errs := validate.Var(test.param, "tcp6_addr")
  1818. if test.expected {
  1819. if !IsEqual(errs, nil) {
  1820. t.Fatalf("Index: %d tcp6_addr failed Error: %s", i, errs)
  1821. }
  1822. } else {
  1823. if IsEqual(errs, nil) {
  1824. t.Fatalf("Index: %d tcp6_addr failed Error: %s", i, errs)
  1825. } else {
  1826. val := getError(errs, "", "")
  1827. if val.Tag() != "tcp6_addr" {
  1828. t.Fatalf("Index: %d tcp6_addr failed Error: %s", i, errs)
  1829. }
  1830. }
  1831. }
  1832. }
  1833. }
  1834. func TestTCP4AddrValidation(t *testing.T) {
  1835. tests := []struct {
  1836. param string
  1837. expected bool
  1838. }{
  1839. {"", false},
  1840. {":80", false},
  1841. {"127.0.0.1:80", true},
  1842. {"[::1]:80", false}, // https://github.com/golang/go/issues/14037
  1843. {"256.0.0.0:1", false},
  1844. {"[::1]", false},
  1845. }
  1846. validate := New()
  1847. for i, test := range tests {
  1848. errs := validate.Var(test.param, "tcp4_addr")
  1849. if test.expected {
  1850. if !IsEqual(errs, nil) {
  1851. t.Fatalf("Index: %d tcp4_addr failed Error: %s", i, errs)
  1852. }
  1853. } else {
  1854. if IsEqual(errs, nil) {
  1855. t.Log(test.param, IsEqual(errs, nil))
  1856. t.Fatalf("Index: %d tcp4_addr failed Error: %s", i, errs)
  1857. } else {
  1858. val := getError(errs, "", "")
  1859. if val.Tag() != "tcp4_addr" {
  1860. t.Fatalf("Index: %d tcp4_addr failed Error: %s", i, errs)
  1861. }
  1862. }
  1863. }
  1864. }
  1865. }
  1866. func TestUDPAddrValidation(t *testing.T) {
  1867. tests := []struct {
  1868. param string
  1869. expected bool
  1870. }{
  1871. {"", false},
  1872. {":80", false},
  1873. {"127.0.0.1:80", true},
  1874. {"[::1]:80", true},
  1875. {"256.0.0.0:1", false},
  1876. {"[::1]", false},
  1877. }
  1878. validate := New()
  1879. for i, test := range tests {
  1880. errs := validate.Var(test.param, "udp_addr")
  1881. if test.expected {
  1882. if !IsEqual(errs, nil) {
  1883. t.Fatalf("Index: %d udp_addr failed Error: %s", i, errs)
  1884. }
  1885. } else {
  1886. if IsEqual(errs, nil) {
  1887. t.Fatalf("Index: %d udp_addr failed Error: %s", i, errs)
  1888. } else {
  1889. val := getError(errs, "", "")
  1890. if val.Tag() != "udp_addr" {
  1891. t.Fatalf("Index: %d udp_addr failed Error: %s", i, errs)
  1892. }
  1893. }
  1894. }
  1895. }
  1896. }
  1897. func TestUDP6AddrValidation(t *testing.T) {
  1898. tests := []struct {
  1899. param string
  1900. expected bool
  1901. }{
  1902. {"", false},
  1903. {":80", false},
  1904. {"127.0.0.1:80", false},
  1905. {"[::1]:80", true},
  1906. {"256.0.0.0:1", false},
  1907. {"[::1]", false},
  1908. }
  1909. validate := New()
  1910. for i, test := range tests {
  1911. errs := validate.Var(test.param, "udp6_addr")
  1912. if test.expected {
  1913. if !IsEqual(errs, nil) {
  1914. t.Fatalf("Index: %d udp6_addr failed Error: %s", i, errs)
  1915. }
  1916. } else {
  1917. if IsEqual(errs, nil) {
  1918. t.Fatalf("Index: %d udp6_addr failed Error: %s", i, errs)
  1919. } else {
  1920. val := getError(errs, "", "")
  1921. if val.Tag() != "udp6_addr" {
  1922. t.Fatalf("Index: %d udp6_addr failed Error: %s", i, errs)
  1923. }
  1924. }
  1925. }
  1926. }
  1927. }
  1928. func TestUDP4AddrValidation(t *testing.T) {
  1929. tests := []struct {
  1930. param string
  1931. expected bool
  1932. }{
  1933. {"", false},
  1934. {":80", false},
  1935. {"127.0.0.1:80", true},
  1936. {"[::1]:80", false}, // https://github.com/golang/go/issues/14037
  1937. {"256.0.0.0:1", false},
  1938. {"[::1]", false},
  1939. }
  1940. validate := New()
  1941. for i, test := range tests {
  1942. errs := validate.Var(test.param, "udp4_addr")
  1943. if test.expected {
  1944. if !IsEqual(errs, nil) {
  1945. t.Fatalf("Index: %d udp4_addr failed Error: %s", i, errs)
  1946. }
  1947. } else {
  1948. if IsEqual(errs, nil) {
  1949. t.Log(test.param, IsEqual(errs, nil))
  1950. t.Fatalf("Index: %d udp4_addr failed Error: %s", i, errs)
  1951. } else {
  1952. val := getError(errs, "", "")
  1953. if val.Tag() != "udp4_addr" {
  1954. t.Fatalf("Index: %d udp4_addr failed Error: %s", i, errs)
  1955. }
  1956. }
  1957. }
  1958. }
  1959. }
  1960. func TestIPAddrValidation(t *testing.T) {
  1961. tests := []struct {
  1962. param string
  1963. expected bool
  1964. }{
  1965. {"", false},
  1966. {"127.0.0.1", true},
  1967. {"127.0.0.1:80", false},
  1968. {"::1", true},
  1969. {"256.0.0.0", false},
  1970. {"localhost", false},
  1971. }
  1972. validate := New()
  1973. for i, test := range tests {
  1974. errs := validate.Var(test.param, "ip_addr")
  1975. if test.expected {
  1976. if !IsEqual(errs, nil) {
  1977. t.Fatalf("Index: %d ip_addr failed Error: %s", i, errs)
  1978. }
  1979. } else {
  1980. if IsEqual(errs, nil) {
  1981. t.Fatalf("Index: %d ip_addr failed Error: %s", i, errs)
  1982. } else {
  1983. val := getError(errs, "", "")
  1984. if val.Tag() != "ip_addr" {
  1985. t.Fatalf("Index: %d ip_addr failed Error: %s", i, errs)
  1986. }
  1987. }
  1988. }
  1989. }
  1990. }
  1991. func TestIP6AddrValidation(t *testing.T) {
  1992. tests := []struct {
  1993. param string
  1994. expected bool
  1995. }{
  1996. {"", false},
  1997. {"127.0.0.1", false}, // https://github.com/golang/go/issues/14037
  1998. {"127.0.0.1:80", false},
  1999. {"::1", true},
  2000. {"0:0:0:0:0:0:0:1", true},
  2001. {"256.0.0.0", false},
  2002. }
  2003. validate := New()
  2004. for i, test := range tests {
  2005. errs := validate.Var(test.param, "ip6_addr")
  2006. if test.expected {
  2007. if !IsEqual(errs, nil) {
  2008. t.Fatalf("Index: %d ip6_addr failed Error: %s", i, errs)
  2009. }
  2010. } else {
  2011. if IsEqual(errs, nil) {
  2012. t.Fatalf("Index: %d ip6_addr failed Error: %s", i, errs)
  2013. } else {
  2014. val := getError(errs, "", "")
  2015. if val.Tag() != "ip6_addr" {
  2016. t.Fatalf("Index: %d ip6_addr failed Error: %s", i, errs)
  2017. }
  2018. }
  2019. }
  2020. }
  2021. }
  2022. func TestIP4AddrValidation(t *testing.T) {
  2023. tests := []struct {
  2024. param string
  2025. expected bool
  2026. }{
  2027. {"", false},
  2028. {"127.0.0.1", true},
  2029. {"127.0.0.1:80", false},
  2030. {"::1", false}, // https://github.com/golang/go/issues/14037
  2031. {"256.0.0.0", false},
  2032. {"localhost", false},
  2033. }
  2034. validate := New()
  2035. for i, test := range tests {
  2036. errs := validate.Var(test.param, "ip4_addr")
  2037. if test.expected {
  2038. if !IsEqual(errs, nil) {
  2039. t.Fatalf("Index: %d ip4_addr failed Error: %s", i, errs)
  2040. }
  2041. } else {
  2042. if IsEqual(errs, nil) {
  2043. t.Log(test.param, IsEqual(errs, nil))
  2044. t.Fatalf("Index: %d ip4_addr failed Error: %s", i, errs)
  2045. } else {
  2046. val := getError(errs, "", "")
  2047. if val.Tag() != "ip4_addr" {
  2048. t.Fatalf("Index: %d ip4_addr failed Error: %s", i, errs)
  2049. }
  2050. }
  2051. }
  2052. }
  2053. }
  2054. func TestUnixAddrValidation(t *testing.T) {
  2055. tests := []struct {
  2056. param string
  2057. expected bool
  2058. }{
  2059. {"", true},
  2060. {"v.sock", true},
  2061. }
  2062. validate := New()
  2063. for i, test := range tests {
  2064. errs := validate.Var(test.param, "unix_addr")
  2065. if test.expected {
  2066. if !IsEqual(errs, nil) {
  2067. t.Fatalf("Index: %d unix_addr failed Error: %s", i, errs)
  2068. }
  2069. } else {
  2070. if IsEqual(errs, nil) {
  2071. t.Log(test.param, IsEqual(errs, nil))
  2072. t.Fatalf("Index: %d unix_addr failed Error: %s", i, errs)
  2073. } else {
  2074. val := getError(errs, "", "")
  2075. if val.Tag() != "unix_addr" {
  2076. t.Fatalf("Index: %d unix_addr failed Error: %s", i, errs)
  2077. }
  2078. }
  2079. }
  2080. }
  2081. }
  2082. func TestSliceMapArrayChanFuncPtrInterfaceRequiredValidation(t *testing.T) {
  2083. validate := New()
  2084. var m map[string]string
  2085. errs := validate.Var(m, "required")
  2086. NotEqual(t, errs, nil)
  2087. AssertError(t, errs, "", "", "", "", "required")
  2088. m = map[string]string{}
  2089. errs = validate.Var(m, "required")
  2090. Equal(t, errs, nil)
  2091. var arr [5]string
  2092. errs = validate.Var(arr, "required")
  2093. NotEqual(t, errs, nil)
  2094. AssertError(t, errs, "", "", "", "", "required")
  2095. arr[0] = "ok"
  2096. errs = validate.Var(arr, "required")
  2097. Equal(t, errs, nil)
  2098. var s []string
  2099. errs = validate.Var(s, "required")
  2100. NotEqual(t, errs, nil)
  2101. AssertError(t, errs, "", "", "", "", "required")
  2102. s = []string{}
  2103. errs = validate.Var(s, "required")
  2104. Equal(t, errs, nil)
  2105. var c chan string
  2106. errs = validate.Var(c, "required")
  2107. NotEqual(t, errs, nil)
  2108. AssertError(t, errs, "", "", "", "", "required")
  2109. c = make(chan string)
  2110. errs = validate.Var(c, "required")
  2111. Equal(t, errs, nil)
  2112. var tst *int
  2113. errs = validate.Var(tst, "required")
  2114. NotEqual(t, errs, nil)
  2115. AssertError(t, errs, "", "", "", "", "required")
  2116. one := 1
  2117. tst = &one
  2118. errs = validate.Var(tst, "required")
  2119. Equal(t, errs, nil)
  2120. var iface interface{}
  2121. errs = validate.Var(iface, "required")
  2122. NotEqual(t, errs, nil)
  2123. AssertError(t, errs, "", "", "", "", "required")
  2124. errs = validate.Var(iface, "omitempty,required")
  2125. Equal(t, errs, nil)
  2126. errs = validate.Var(iface, "")
  2127. Equal(t, errs, nil)
  2128. errs = validate.VarWithValue(nil, iface, "")
  2129. Equal(t, errs, nil)
  2130. var f func(string)
  2131. errs = validate.Var(f, "required")
  2132. NotEqual(t, errs, nil)
  2133. AssertError(t, errs, "", "", "", "", "required")
  2134. f = func(name string) {}
  2135. errs = validate.Var(f, "required")
  2136. Equal(t, errs, nil)
  2137. }
  2138. func TestDatePtrValidationIssueValidation(t *testing.T) {
  2139. type Test struct {
  2140. LastViewed *time.Time
  2141. Reminder *time.Time
  2142. }
  2143. test := &Test{}
  2144. validate := New()
  2145. errs := validate.Struct(test)
  2146. Equal(t, errs, nil)
  2147. }
  2148. func TestCommaAndPipeObfuscationValidation(t *testing.T) {
  2149. s := "My Name Is, |joeybloggs|"
  2150. validate := New()
  2151. errs := validate.Var(s, "excludesall=0x2C")
  2152. NotEqual(t, errs, nil)
  2153. AssertError(t, errs, "", "", "", "", "excludesall")
  2154. errs = validate.Var(s, "excludesall=0x7C")
  2155. NotEqual(t, errs, nil)
  2156. AssertError(t, errs, "", "", "", "", "excludesall")
  2157. }
  2158. func TestBadKeyValidation(t *testing.T) {
  2159. type Test struct {
  2160. Name string `validate:"required, "`
  2161. }
  2162. tst := &Test{
  2163. Name: "test",
  2164. }
  2165. validate := New()
  2166. PanicMatches(t, func() { validate.Struct(tst) }, "Undefined validation function ' ' on field 'Name'")
  2167. type Test2 struct {
  2168. Name string `validate:"required,,len=2"`
  2169. }
  2170. tst2 := &Test2{
  2171. Name: "test",
  2172. }
  2173. PanicMatches(t, func() { validate.Struct(tst2) }, "Invalid validation tag on field 'Name'")
  2174. }
  2175. func TestInterfaceErrValidation(t *testing.T) {
  2176. var v2 interface{} = 1
  2177. var v1 interface{} = v2
  2178. validate := New()
  2179. errs := validate.Var(v1, "len=1")
  2180. Equal(t, errs, nil)
  2181. errs = validate.Var(v2, "len=1")
  2182. Equal(t, errs, nil)
  2183. type ExternalCMD struct {
  2184. Userid string `json:"userid"`
  2185. Action uint32 `json:"action"`
  2186. Data interface{} `json:"data,omitempty" validate:"required"`
  2187. }
  2188. s := &ExternalCMD{
  2189. Userid: "123456",
  2190. Action: 10000,
  2191. // Data: 1,
  2192. }
  2193. errs = validate.Struct(s)
  2194. NotEqual(t, errs, nil)
  2195. Equal(t, len(errs.(ValidationErrors)), 1)
  2196. AssertError(t, errs, "ExternalCMD.Data", "ExternalCMD.Data", "Data", "Data", "required")
  2197. type ExternalCMD2 struct {
  2198. Userid string `json:"userid"`
  2199. Action uint32 `json:"action"`
  2200. Data interface{} `json:"data,omitempty" validate:"len=1"`
  2201. }
  2202. s2 := &ExternalCMD2{
  2203. Userid: "123456",
  2204. Action: 10000,
  2205. // Data: 1,
  2206. }
  2207. errs = validate.Struct(s2)
  2208. NotEqual(t, errs, nil)
  2209. Equal(t, len(errs.(ValidationErrors)), 1)
  2210. AssertError(t, errs, "ExternalCMD2.Data", "ExternalCMD2.Data", "Data", "Data", "len")
  2211. s3 := &ExternalCMD2{
  2212. Userid: "123456",
  2213. Action: 10000,
  2214. Data: 2,
  2215. }
  2216. errs = validate.Struct(s3)
  2217. NotEqual(t, errs, nil)
  2218. Equal(t, len(errs.(ValidationErrors)), 1)
  2219. AssertError(t, errs, "ExternalCMD2.Data", "ExternalCMD2.Data", "Data", "Data", "len")
  2220. type Inner struct {
  2221. Name string `validate:"required"`
  2222. }
  2223. inner := &Inner{
  2224. Name: "",
  2225. }
  2226. s4 := &ExternalCMD{
  2227. Userid: "123456",
  2228. Action: 10000,
  2229. Data: inner,
  2230. }
  2231. errs = validate.Struct(s4)
  2232. NotEqual(t, errs, nil)
  2233. Equal(t, len(errs.(ValidationErrors)), 1)
  2234. AssertError(t, errs, "ExternalCMD.Data.Name", "ExternalCMD.Data.Name", "Name", "Name", "required")
  2235. type TestMapStructPtr struct {
  2236. Errs map[int]interface{} `validate:"gt=0,dive,len=2"`
  2237. }
  2238. mip := map[int]interface{}{0: &Inner{"ok"}, 3: nil, 4: &Inner{"ok"}}
  2239. msp := &TestMapStructPtr{
  2240. Errs: mip,
  2241. }
  2242. errs = validate.Struct(msp)
  2243. NotEqual(t, errs, nil)
  2244. Equal(t, len(errs.(ValidationErrors)), 1)
  2245. AssertError(t, errs, "TestMapStructPtr.Errs[3]", "TestMapStructPtr.Errs[3]", "Errs[3]", "Errs[3]", "len")
  2246. type TestMultiDimensionalStructs struct {
  2247. Errs [][]interface{} `validate:"gt=0,dive,dive"`
  2248. }
  2249. var errStructArray [][]interface{}
  2250. errStructArray = append(errStructArray, []interface{}{&Inner{"ok"}, &Inner{""}, &Inner{""}})
  2251. errStructArray = append(errStructArray, []interface{}{&Inner{"ok"}, &Inner{""}, &Inner{""}})
  2252. tms := &TestMultiDimensionalStructs{
  2253. Errs: errStructArray,
  2254. }
  2255. errs = validate.Struct(tms)
  2256. NotEqual(t, errs, nil)
  2257. Equal(t, len(errs.(ValidationErrors)), 4)
  2258. AssertError(t, errs, "TestMultiDimensionalStructs.Errs[0][1].Name", "TestMultiDimensionalStructs.Errs[0][1].Name", "Name", "Name", "required")
  2259. AssertError(t, errs, "TestMultiDimensionalStructs.Errs[0][2].Name", "TestMultiDimensionalStructs.Errs[0][2].Name", "Name", "Name", "required")
  2260. AssertError(t, errs, "TestMultiDimensionalStructs.Errs[1][1].Name", "TestMultiDimensionalStructs.Errs[1][1].Name", "Name", "Name", "required")
  2261. AssertError(t, errs, "TestMultiDimensionalStructs.Errs[1][2].Name", "TestMultiDimensionalStructs.Errs[1][2].Name", "Name", "Name", "required")
  2262. type TestMultiDimensionalStructsPtr2 struct {
  2263. Errs [][]*Inner `validate:"gt=0,dive,dive,required"`
  2264. }
  2265. var errStructPtr2Array [][]*Inner
  2266. errStructPtr2Array = append(errStructPtr2Array, []*Inner{{"ok"}, {""}, {""}})
  2267. errStructPtr2Array = append(errStructPtr2Array, []*Inner{{"ok"}, {""}, {""}})
  2268. errStructPtr2Array = append(errStructPtr2Array, []*Inner{{"ok"}, {""}, nil})
  2269. tmsp2 := &TestMultiDimensionalStructsPtr2{
  2270. Errs: errStructPtr2Array,
  2271. }
  2272. errs = validate.Struct(tmsp2)
  2273. NotEqual(t, errs, nil)
  2274. Equal(t, len(errs.(ValidationErrors)), 6)
  2275. AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[0][1].Name", "TestMultiDimensionalStructsPtr2.Errs[0][1].Name", "Name", "Name", "required")
  2276. AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[0][2].Name", "TestMultiDimensionalStructsPtr2.Errs[0][2].Name", "Name", "Name", "required")
  2277. AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[1][1].Name", "TestMultiDimensionalStructsPtr2.Errs[1][1].Name", "Name", "Name", "required")
  2278. AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[1][2].Name", "TestMultiDimensionalStructsPtr2.Errs[1][2].Name", "Name", "Name", "required")
  2279. AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[2][1].Name", "TestMultiDimensionalStructsPtr2.Errs[2][1].Name", "Name", "Name", "required")
  2280. AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[2][2]", "TestMultiDimensionalStructsPtr2.Errs[2][2]", "Errs[2][2]", "Errs[2][2]", "required")
  2281. m := map[int]interface{}{0: "ok", 3: "", 4: "ok"}
  2282. errs = validate.Var(m, "len=3,dive,len=2")
  2283. NotEqual(t, errs, nil)
  2284. Equal(t, len(errs.(ValidationErrors)), 1)
  2285. AssertError(t, errs, "[3]", "[3]", "[3]", "[3]", "len")
  2286. errs = validate.Var(m, "len=2,dive,required")
  2287. NotEqual(t, errs, nil)
  2288. Equal(t, len(errs.(ValidationErrors)), 1)
  2289. AssertError(t, errs, "", "", "", "", "len")
  2290. arr := []interface{}{"ok", "", "ok"}
  2291. errs = validate.Var(arr, "len=3,dive,len=2")
  2292. NotEqual(t, errs, nil)
  2293. Equal(t, len(errs.(ValidationErrors)), 1)
  2294. AssertError(t, errs, "[1]", "[1]", "[1]", "[1]", "len")
  2295. errs = validate.Var(arr, "len=2,dive,required")
  2296. NotEqual(t, errs, nil)
  2297. Equal(t, len(errs.(ValidationErrors)), 1)
  2298. AssertError(t, errs, "", "", "", "", "len")
  2299. type MyStruct struct {
  2300. A, B string
  2301. C interface{}
  2302. }
  2303. var a MyStruct
  2304. a.A = "value"
  2305. a.C = "nu"
  2306. errs = validate.Struct(a)
  2307. Equal(t, errs, nil)
  2308. }
  2309. func TestMapDiveValidation(t *testing.T) {
  2310. validate := New()
  2311. n := map[int]interface{}{0: nil}
  2312. errs := validate.Var(n, "omitempty,required")
  2313. Equal(t, errs, nil)
  2314. m := map[int]string{0: "ok", 3: "", 4: "ok"}
  2315. errs = validate.Var(m, "len=3,dive,required")
  2316. NotEqual(t, errs, nil)
  2317. Equal(t, len(errs.(ValidationErrors)), 1)
  2318. AssertError(t, errs, "[3]", "[3]", "[3]", "[3]", "required")
  2319. errs = validate.Var(m, "len=2,dive,required")
  2320. NotEqual(t, errs, nil)
  2321. Equal(t, len(errs.(ValidationErrors)), 1)
  2322. AssertError(t, errs, "", "", "", "", "len")
  2323. type Inner struct {
  2324. Name string `validate:"required"`
  2325. }
  2326. type TestMapStruct struct {
  2327. Errs map[int]Inner `validate:"gt=0,dive"`
  2328. }
  2329. mi := map[int]Inner{0: {"ok"}, 3: {""}, 4: {"ok"}}
  2330. ms := &TestMapStruct{
  2331. Errs: mi,
  2332. }
  2333. errs = validate.Struct(ms)
  2334. NotEqual(t, errs, nil)
  2335. Equal(t, len(errs.(ValidationErrors)), 1)
  2336. AssertError(t, errs, "TestMapStruct.Errs[3].Name", "TestMapStruct.Errs[3].Name", "Name", "Name", "required")
  2337. // for full test coverage
  2338. s := fmt.Sprint(errs.Error())
  2339. NotEqual(t, s, "")
  2340. type TestMapTimeStruct struct {
  2341. Errs map[int]*time.Time `validate:"gt=0,dive,required"`
  2342. }
  2343. t1 := time.Now().UTC()
  2344. mta := map[int]*time.Time{0: &t1, 3: nil, 4: nil}
  2345. mt := &TestMapTimeStruct{
  2346. Errs: mta,
  2347. }
  2348. errs = validate.Struct(mt)
  2349. NotEqual(t, errs, nil)
  2350. Equal(t, len(errs.(ValidationErrors)), 2)
  2351. AssertError(t, errs, "TestMapTimeStruct.Errs[3]", "TestMapTimeStruct.Errs[3]", "Errs[3]", "Errs[3]", "required")
  2352. AssertError(t, errs, "TestMapTimeStruct.Errs[4]", "TestMapTimeStruct.Errs[4]", "Errs[4]", "Errs[4]", "required")
  2353. type TestMapStructPtr struct {
  2354. Errs map[int]*Inner `validate:"gt=0,dive,required"`
  2355. }
  2356. mip := map[int]*Inner{0: {"ok"}, 3: nil, 4: {"ok"}}
  2357. msp := &TestMapStructPtr{
  2358. Errs: mip,
  2359. }
  2360. errs = validate.Struct(msp)
  2361. NotEqual(t, errs, nil)
  2362. Equal(t, len(errs.(ValidationErrors)), 1)
  2363. AssertError(t, errs, "TestMapStructPtr.Errs[3]", "TestMapStructPtr.Errs[3]", "Errs[3]", "Errs[3]", "required")
  2364. type TestMapStructPtr2 struct {
  2365. Errs map[int]*Inner `validate:"gt=0,dive,omitempty,required"`
  2366. }
  2367. mip2 := map[int]*Inner{0: {"ok"}, 3: nil, 4: {"ok"}}
  2368. msp2 := &TestMapStructPtr2{
  2369. Errs: mip2,
  2370. }
  2371. errs = validate.Struct(msp2)
  2372. Equal(t, errs, nil)
  2373. v2 := New()
  2374. v2.RegisterTagNameFunc(func(fld reflect.StructField) string {
  2375. name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
  2376. if name == "-" {
  2377. return ""
  2378. }
  2379. return name
  2380. })
  2381. type MapDiveJSONTest struct {
  2382. Map map[string]string `validate:"required,gte=1,dive,gte=1" json:"MyName"`
  2383. }
  2384. mdjt := &MapDiveJSONTest{
  2385. Map: map[string]string{
  2386. "Key1": "Value1",
  2387. "Key2": "",
  2388. },
  2389. }
  2390. err := v2.Struct(mdjt)
  2391. NotEqual(t, err, nil)
  2392. errs = err.(ValidationErrors)
  2393. fe := getError(errs, "MapDiveJSONTest.MyName[Key2]", "MapDiveJSONTest.Map[Key2]")
  2394. NotEqual(t, fe, nil)
  2395. Equal(t, fe.Tag(), "gte")
  2396. Equal(t, fe.ActualTag(), "gte")
  2397. Equal(t, fe.Field(), "MyName[Key2]")
  2398. Equal(t, fe.StructField(), "Map[Key2]")
  2399. }
  2400. func TestArrayDiveValidation(t *testing.T) {
  2401. validate := New()
  2402. arr := []string{"ok", "", "ok"}
  2403. errs := validate.Var(arr, "len=3,dive,required")
  2404. NotEqual(t, errs, nil)
  2405. Equal(t, len(errs.(ValidationErrors)), 1)
  2406. AssertError(t, errs, "[1]", "[1]", "[1]", "[1]", "required")
  2407. errs = validate.Var(arr, "len=2,dive,required")
  2408. NotEqual(t, errs, nil)
  2409. Equal(t, len(errs.(ValidationErrors)), 1)
  2410. AssertError(t, errs, "", "", "", "", "len")
  2411. type BadDive struct {
  2412. Name string `validate:"dive"`
  2413. }
  2414. bd := &BadDive{
  2415. Name: "TEST",
  2416. }
  2417. PanicMatches(t, func() { validate.Struct(bd) }, "dive error! can't dive on a non slice or map")
  2418. type Test struct {
  2419. Errs []string `validate:"gt=0,dive,required"`
  2420. }
  2421. test := &Test{
  2422. Errs: []string{"ok", "", "ok"},
  2423. }
  2424. errs = validate.Struct(test)
  2425. NotEqual(t, errs, nil)
  2426. Equal(t, len(errs.(ValidationErrors)), 1)
  2427. AssertError(t, errs, "Test.Errs[1]", "Test.Errs[1]", "Errs[1]", "Errs[1]", "required")
  2428. test = &Test{
  2429. Errs: []string{"ok", "ok", ""},
  2430. }
  2431. errs = validate.Struct(test)
  2432. NotEqual(t, errs, nil)
  2433. Equal(t, len(errs.(ValidationErrors)), 1)
  2434. AssertError(t, errs, "Test.Errs[2]", "Test.Errs[2]", "Errs[2]", "Errs[2]", "required")
  2435. type TestMultiDimensional struct {
  2436. Errs [][]string `validate:"gt=0,dive,dive,required"`
  2437. }
  2438. var errArray [][]string
  2439. errArray = append(errArray, []string{"ok", "", ""})
  2440. errArray = append(errArray, []string{"ok", "", ""})
  2441. tm := &TestMultiDimensional{
  2442. Errs: errArray,
  2443. }
  2444. errs = validate.Struct(tm)
  2445. NotEqual(t, errs, nil)
  2446. Equal(t, len(errs.(ValidationErrors)), 4)
  2447. AssertError(t, errs, "TestMultiDimensional.Errs[0][1]", "TestMultiDimensional.Errs[0][1]", "Errs[0][1]", "Errs[0][1]", "required")
  2448. AssertError(t, errs, "TestMultiDimensional.Errs[0][2]", "TestMultiDimensional.Errs[0][2]", "Errs[0][2]", "Errs[0][2]", "required")
  2449. AssertError(t, errs, "TestMultiDimensional.Errs[1][1]", "TestMultiDimensional.Errs[1][1]", "Errs[1][1]", "Errs[1][1]", "required")
  2450. AssertError(t, errs, "TestMultiDimensional.Errs[1][2]", "TestMultiDimensional.Errs[1][2]", "Errs[1][2]", "Errs[1][2]", "required")
  2451. type Inner struct {
  2452. Name string `validate:"required"`
  2453. }
  2454. type TestMultiDimensionalStructs struct {
  2455. Errs [][]Inner `validate:"gt=0,dive,dive"`
  2456. }
  2457. var errStructArray [][]Inner
  2458. errStructArray = append(errStructArray, []Inner{{"ok"}, {""}, {""}})
  2459. errStructArray = append(errStructArray, []Inner{{"ok"}, {""}, {""}})
  2460. tms := &TestMultiDimensionalStructs{
  2461. Errs: errStructArray,
  2462. }
  2463. errs = validate.Struct(tms)
  2464. NotEqual(t, errs, nil)
  2465. Equal(t, len(errs.(ValidationErrors)), 4)
  2466. AssertError(t, errs, "TestMultiDimensionalStructs.Errs[0][1].Name", "TestMultiDimensionalStructs.Errs[0][1].Name", "Name", "Name", "required")
  2467. AssertError(t, errs, "TestMultiDimensionalStructs.Errs[0][2].Name", "TestMultiDimensionalStructs.Errs[0][2].Name", "Name", "Name", "required")
  2468. AssertError(t, errs, "TestMultiDimensionalStructs.Errs[1][1].Name", "TestMultiDimensionalStructs.Errs[1][1].Name", "Name", "Name", "required")
  2469. AssertError(t, errs, "TestMultiDimensionalStructs.Errs[1][2].Name", "TestMultiDimensionalStructs.Errs[1][2].Name", "Name", "Name", "required")
  2470. type TestMultiDimensionalStructsPtr struct {
  2471. Errs [][]*Inner `validate:"gt=0,dive,dive"`
  2472. }
  2473. var errStructPtrArray [][]*Inner
  2474. errStructPtrArray = append(errStructPtrArray, []*Inner{{"ok"}, {""}, {""}})
  2475. errStructPtrArray = append(errStructPtrArray, []*Inner{{"ok"}, {""}, {""}})
  2476. errStructPtrArray = append(errStructPtrArray, []*Inner{{"ok"}, {""}, nil})
  2477. tmsp := &TestMultiDimensionalStructsPtr{
  2478. Errs: errStructPtrArray,
  2479. }
  2480. errs = validate.Struct(tmsp)
  2481. NotEqual(t, errs, nil)
  2482. Equal(t, len(errs.(ValidationErrors)), 5)
  2483. AssertError(t, errs, "TestMultiDimensionalStructsPtr.Errs[0][1].Name", "TestMultiDimensionalStructsPtr.Errs[0][1].Name", "Name", "Name", "required")
  2484. AssertError(t, errs, "TestMultiDimensionalStructsPtr.Errs[0][2].Name", "TestMultiDimensionalStructsPtr.Errs[0][2].Name", "Name", "Name", "required")
  2485. AssertError(t, errs, "TestMultiDimensionalStructsPtr.Errs[1][1].Name", "TestMultiDimensionalStructsPtr.Errs[1][1].Name", "Name", "Name", "required")
  2486. AssertError(t, errs, "TestMultiDimensionalStructsPtr.Errs[1][2].Name", "TestMultiDimensionalStructsPtr.Errs[1][2].Name", "Name", "Name", "required")
  2487. AssertError(t, errs, "TestMultiDimensionalStructsPtr.Errs[2][1].Name", "TestMultiDimensionalStructsPtr.Errs[2][1].Name", "Name", "Name", "required")
  2488. // for full test coverage
  2489. s := fmt.Sprint(errs.Error())
  2490. NotEqual(t, s, "")
  2491. type TestMultiDimensionalStructsPtr2 struct {
  2492. Errs [][]*Inner `validate:"gt=0,dive,dive,required"`
  2493. }
  2494. var errStructPtr2Array [][]*Inner
  2495. errStructPtr2Array = append(errStructPtr2Array, []*Inner{{"ok"}, {""}, {""}})
  2496. errStructPtr2Array = append(errStructPtr2Array, []*Inner{{"ok"}, {""}, {""}})
  2497. errStructPtr2Array = append(errStructPtr2Array, []*Inner{{"ok"}, {""}, nil})
  2498. tmsp2 := &TestMultiDimensionalStructsPtr2{
  2499. Errs: errStructPtr2Array,
  2500. }
  2501. errs = validate.Struct(tmsp2)
  2502. NotEqual(t, errs, nil)
  2503. Equal(t, len(errs.(ValidationErrors)), 6)
  2504. AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[0][1].Name", "TestMultiDimensionalStructsPtr2.Errs[0][1].Name", "Name", "Name", "required")
  2505. AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[0][2].Name", "TestMultiDimensionalStructsPtr2.Errs[0][2].Name", "Name", "Name", "required")
  2506. AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[1][1].Name", "TestMultiDimensionalStructsPtr2.Errs[1][1].Name", "Name", "Name", "required")
  2507. AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[1][2].Name", "TestMultiDimensionalStructsPtr2.Errs[1][2].Name", "Name", "Name", "required")
  2508. AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[2][1].Name", "TestMultiDimensionalStructsPtr2.Errs[2][1].Name", "Name", "Name", "required")
  2509. AssertError(t, errs, "TestMultiDimensionalStructsPtr2.Errs[2][2]", "TestMultiDimensionalStructsPtr2.Errs[2][2]", "Errs[2][2]", "Errs[2][2]", "required")
  2510. type TestMultiDimensionalStructsPtr3 struct {
  2511. Errs [][]*Inner `validate:"gt=0,dive,dive,omitempty"`
  2512. }
  2513. var errStructPtr3Array [][]*Inner
  2514. errStructPtr3Array = append(errStructPtr3Array, []*Inner{{"ok"}, {""}, {""}})
  2515. errStructPtr3Array = append(errStructPtr3Array, []*Inner{{"ok"}, {""}, {""}})
  2516. errStructPtr3Array = append(errStructPtr3Array, []*Inner{{"ok"}, {""}, nil})
  2517. tmsp3 := &TestMultiDimensionalStructsPtr3{
  2518. Errs: errStructPtr3Array,
  2519. }
  2520. errs = validate.Struct(tmsp3)
  2521. NotEqual(t, errs, nil)
  2522. Equal(t, len(errs.(ValidationErrors)), 5)
  2523. AssertError(t, errs, "TestMultiDimensionalStructsPtr3.Errs[0][1].Name", "TestMultiDimensionalStructsPtr3.Errs[0][1].Name", "Name", "Name", "required")
  2524. AssertError(t, errs, "TestMultiDimensionalStructsPtr3.Errs[0][2].Name", "TestMultiDimensionalStructsPtr3.Errs[0][2].Name", "Name", "Name", "required")
  2525. AssertError(t, errs, "TestMultiDimensionalStructsPtr3.Errs[1][1].Name", "TestMultiDimensionalStructsPtr3.Errs[1][1].Name", "Name", "Name", "required")
  2526. AssertError(t, errs, "TestMultiDimensionalStructsPtr3.Errs[1][2].Name", "TestMultiDimensionalStructsPtr3.Errs[1][2].Name", "Name", "Name", "required")
  2527. AssertError(t, errs, "TestMultiDimensionalStructsPtr3.Errs[2][1].Name", "TestMultiDimensionalStructsPtr3.Errs[2][1].Name", "Name", "Name", "required")
  2528. type TestMultiDimensionalTimeTime struct {
  2529. Errs [][]*time.Time `validate:"gt=0,dive,dive,required"`
  2530. }
  2531. var errTimePtr3Array [][]*time.Time
  2532. t1 := time.Now().UTC()
  2533. t2 := time.Now().UTC()
  2534. t3 := time.Now().UTC().Add(time.Hour * 24)
  2535. errTimePtr3Array = append(errTimePtr3Array, []*time.Time{&t1, &t2, &t3})
  2536. errTimePtr3Array = append(errTimePtr3Array, []*time.Time{&t1, &t2, nil})
  2537. errTimePtr3Array = append(errTimePtr3Array, []*time.Time{&t1, nil, nil})
  2538. tmtp3 := &TestMultiDimensionalTimeTime{
  2539. Errs: errTimePtr3Array,
  2540. }
  2541. errs = validate.Struct(tmtp3)
  2542. NotEqual(t, errs, nil)
  2543. Equal(t, len(errs.(ValidationErrors)), 3)
  2544. AssertError(t, errs, "TestMultiDimensionalTimeTime.Errs[1][2]", "TestMultiDimensionalTimeTime.Errs[1][2]", "Errs[1][2]", "Errs[1][2]", "required")
  2545. AssertError(t, errs, "TestMultiDimensionalTimeTime.Errs[2][1]", "TestMultiDimensionalTimeTime.Errs[2][1]", "Errs[2][1]", "Errs[2][1]", "required")
  2546. AssertError(t, errs, "TestMultiDimensionalTimeTime.Errs[2][2]", "TestMultiDimensionalTimeTime.Errs[2][2]", "Errs[2][2]", "Errs[2][2]", "required")
  2547. type TestMultiDimensionalTimeTime2 struct {
  2548. Errs [][]*time.Time `validate:"gt=0,dive,dive,required"`
  2549. }
  2550. var errTimeArray [][]*time.Time
  2551. t1 = time.Now().UTC()
  2552. t2 = time.Now().UTC()
  2553. t3 = time.Now().UTC().Add(time.Hour * 24)
  2554. errTimeArray = append(errTimeArray, []*time.Time{&t1, &t2, &t3})
  2555. errTimeArray = append(errTimeArray, []*time.Time{&t1, &t2, nil})
  2556. errTimeArray = append(errTimeArray, []*time.Time{&t1, nil, nil})
  2557. tmtp := &TestMultiDimensionalTimeTime2{
  2558. Errs: errTimeArray,
  2559. }
  2560. errs = validate.Struct(tmtp)
  2561. NotEqual(t, errs, nil)
  2562. Equal(t, len(errs.(ValidationErrors)), 3)
  2563. AssertError(t, errs, "TestMultiDimensionalTimeTime2.Errs[1][2]", "TestMultiDimensionalTimeTime2.Errs[1][2]", "Errs[1][2]", "Errs[1][2]", "required")
  2564. AssertError(t, errs, "TestMultiDimensionalTimeTime2.Errs[2][1]", "TestMultiDimensionalTimeTime2.Errs[2][1]", "Errs[2][1]", "Errs[2][1]", "required")
  2565. AssertError(t, errs, "TestMultiDimensionalTimeTime2.Errs[2][2]", "TestMultiDimensionalTimeTime2.Errs[2][2]", "Errs[2][2]", "Errs[2][2]", "required")
  2566. }
  2567. func TestNilStructPointerValidation(t *testing.T) {
  2568. type Inner struct {
  2569. Data string
  2570. }
  2571. type Outer struct {
  2572. Inner *Inner `validate:"omitempty"`
  2573. }
  2574. inner := &Inner{
  2575. Data: "test",
  2576. }
  2577. outer := &Outer{
  2578. Inner: inner,
  2579. }
  2580. validate := New()
  2581. errs := validate.Struct(outer)
  2582. Equal(t, errs, nil)
  2583. outer = &Outer{
  2584. Inner: nil,
  2585. }
  2586. errs = validate.Struct(outer)
  2587. Equal(t, errs, nil)
  2588. type Inner2 struct {
  2589. Data string
  2590. }
  2591. type Outer2 struct {
  2592. Inner2 *Inner2 `validate:"required"`
  2593. }
  2594. inner2 := &Inner2{
  2595. Data: "test",
  2596. }
  2597. outer2 := &Outer2{
  2598. Inner2: inner2,
  2599. }
  2600. errs = validate.Struct(outer2)
  2601. Equal(t, errs, nil)
  2602. outer2 = &Outer2{
  2603. Inner2: nil,
  2604. }
  2605. errs = validate.Struct(outer2)
  2606. NotEqual(t, errs, nil)
  2607. AssertError(t, errs, "Outer2.Inner2", "Outer2.Inner2", "Inner2", "Inner2", "required")
  2608. type Inner3 struct {
  2609. Data string
  2610. }
  2611. type Outer3 struct {
  2612. Inner3 *Inner3
  2613. }
  2614. inner3 := &Inner3{
  2615. Data: "test",
  2616. }
  2617. outer3 := &Outer3{
  2618. Inner3: inner3,
  2619. }
  2620. errs = validate.Struct(outer3)
  2621. Equal(t, errs, nil)
  2622. type Inner4 struct {
  2623. Data string
  2624. }
  2625. type Outer4 struct {
  2626. Inner4 *Inner4 `validate:"-"`
  2627. }
  2628. inner4 := &Inner4{
  2629. Data: "test",
  2630. }
  2631. outer4 := &Outer4{
  2632. Inner4: inner4,
  2633. }
  2634. errs = validate.Struct(outer4)
  2635. Equal(t, errs, nil)
  2636. }
  2637. func TestSSNValidation(t *testing.T) {
  2638. tests := []struct {
  2639. param string
  2640. expected bool
  2641. }{
  2642. {"", false},
  2643. {"00-90-8787", false},
  2644. {"66690-76", false},
  2645. {"191 60 2869", true},
  2646. {"191-60-2869", true},
  2647. }
  2648. validate := New()
  2649. for i, test := range tests {
  2650. errs := validate.Var(test.param, "ssn")
  2651. if test.expected {
  2652. if !IsEqual(errs, nil) {
  2653. t.Fatalf("Index: %d SSN failed Error: %s", i, errs)
  2654. }
  2655. } else {
  2656. if IsEqual(errs, nil) {
  2657. t.Fatalf("Index: %d SSN failed Error: %s", i, errs)
  2658. } else {
  2659. val := getError(errs, "", "")
  2660. if val.Tag() != "ssn" {
  2661. t.Fatalf("Index: %d Latitude failed Error: %s", i, errs)
  2662. }
  2663. }
  2664. }
  2665. }
  2666. }
  2667. func TestLongitudeValidation(t *testing.T) {
  2668. tests := []struct {
  2669. param interface{}
  2670. expected bool
  2671. }{
  2672. {"", false},
  2673. {"-180.000", true},
  2674. {"180.1", false},
  2675. {"+73.234", true},
  2676. {"+382.3811", false},
  2677. {"23.11111111", true},
  2678. {uint(180), true},
  2679. {float32(-180.0), true},
  2680. {-180, true},
  2681. {180.1, false},
  2682. }
  2683. validate := New()
  2684. for i, test := range tests {
  2685. errs := validate.Var(test.param, "longitude")
  2686. if test.expected {
  2687. if !IsEqual(errs, nil) {
  2688. t.Fatalf("Index: %d Longitude failed Error: %s", i, errs)
  2689. }
  2690. } else {
  2691. if IsEqual(errs, nil) {
  2692. t.Fatalf("Index: %d Longitude failed Error: %s", i, errs)
  2693. } else {
  2694. val := getError(errs, "", "")
  2695. if val.Tag() != "longitude" {
  2696. t.Fatalf("Index: %d Longitude failed Error: %s", i, errs)
  2697. }
  2698. }
  2699. }
  2700. }
  2701. PanicMatches(t, func() { validate.Var(true, "longitude") }, "Bad field type bool")
  2702. }
  2703. func TestLatitudeValidation(t *testing.T) {
  2704. tests := []struct {
  2705. param interface{}
  2706. expected bool
  2707. }{
  2708. {"", false},
  2709. {"-90.000", true},
  2710. {"+90", true},
  2711. {"47.1231231", true},
  2712. {"+99.9", false},
  2713. {"108", false},
  2714. {uint(90), true},
  2715. {float32(-90.0), true},
  2716. {-90, true},
  2717. {90.1, false},
  2718. }
  2719. validate := New()
  2720. for i, test := range tests {
  2721. errs := validate.Var(test.param, "latitude")
  2722. if test.expected {
  2723. if !IsEqual(errs, nil) {
  2724. t.Fatalf("Index: %d Latitude failed Error: %s", i, errs)
  2725. }
  2726. } else {
  2727. if IsEqual(errs, nil) {
  2728. t.Fatalf("Index: %d Latitude failed Error: %s", i, errs)
  2729. } else {
  2730. val := getError(errs, "", "")
  2731. if val.Tag() != "latitude" {
  2732. t.Fatalf("Index: %d Latitude failed Error: %s", i, errs)
  2733. }
  2734. }
  2735. }
  2736. }
  2737. PanicMatches(t, func() { validate.Var(true, "latitude") }, "Bad field type bool")
  2738. }
  2739. func TestDataURIValidation(t *testing.T) {
  2740. tests := []struct {
  2741. param string
  2742. expected bool
  2743. }{
  2744. {"data:image/png;base64,TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4=", true},
  2745. {"data:text/plain;base64,Vml2YW11cyBmZXJtZW50dW0gc2VtcGVyIHBvcnRhLg==", true},
  2746. {"image/gif;base64,U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==", false},
  2747. {"data:image/gif;base64,MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuMPNS1Ufof9EW/M98FNw" +
  2748. "UAKrwflsqVxaxQjBQnHQmiI7Vac40t8x7pIb8gLGV6wL7sBTJiPovJ0V7y7oc0Ye" +
  2749. "rhKh0Rm4skP2z/jHwwZICgGzBvA0rH8xlhUiTvcwDCJ0kc+fh35hNt8srZQM4619" +
  2750. "FTgB66Xmp4EtVyhpQV+t02g6NzK72oZI0vnAvqhpkxLeLiMCyrI416wHm5Tkukhx" +
  2751. "QmcL2a6hNOyu0ixX/x2kSFXApEnVrJ+/IxGyfyw8kf4N2IZpW5nEP847lpfj0SZZ" +
  2752. "Fwrd1mnfnDbYohX2zRptLy2ZUn06Qo9pkG5ntvFEPo9bfZeULtjYzIl6K8gJ2uGZ" + "HQIDAQAB", true},
  2753. {"data:image/png;base64,12345", false},
  2754. {"", false},
  2755. {"data:text,:;base85,U3VzcGVuZGlzc2UgbGVjdHVzIGxlbw==", false},
  2756. }
  2757. validate := New()
  2758. for i, test := range tests {
  2759. errs := validate.Var(test.param, "datauri")
  2760. if test.expected {
  2761. if !IsEqual(errs, nil) {
  2762. t.Fatalf("Index: %d DataURI failed Error: %s", i, errs)
  2763. }
  2764. } else {
  2765. if IsEqual(errs, nil) {
  2766. t.Fatalf("Index: %d DataURI failed Error: %s", i, errs)
  2767. } else {
  2768. val := getError(errs, "", "")
  2769. if val.Tag() != "datauri" {
  2770. t.Fatalf("Index: %d DataURI failed Error: %s", i, errs)
  2771. }
  2772. }
  2773. }
  2774. }
  2775. }
  2776. func TestMultibyteValidation(t *testing.T) {
  2777. tests := []struct {
  2778. param string
  2779. expected bool
  2780. }{
  2781. {"", true},
  2782. {"abc", false},
  2783. {"123", false},
  2784. {"<>@;.-=", false},
  2785. {"ひらがな・カタカナ、.漢字", true},
  2786. {"あいうえお foobar", true},
  2787. {"test@example.com", true},
  2788. {"test@example.com", true},
  2789. {"1234abcDExyz", true},
  2790. {"カタカナ", true},
  2791. }
  2792. validate := New()
  2793. for i, test := range tests {
  2794. errs := validate.Var(test.param, "multibyte")
  2795. if test.expected {
  2796. if !IsEqual(errs, nil) {
  2797. t.Fatalf("Index: %d Multibyte failed Error: %s", i, errs)
  2798. }
  2799. } else {
  2800. if IsEqual(errs, nil) {
  2801. t.Fatalf("Index: %d Multibyte failed Error: %s", i, errs)
  2802. } else {
  2803. val := getError(errs, "", "")
  2804. if val.Tag() != "multibyte" {
  2805. t.Fatalf("Index: %d Multibyte failed Error: %s", i, errs)
  2806. }
  2807. }
  2808. }
  2809. }
  2810. }
  2811. func TestPrintableASCIIValidation(t *testing.T) {
  2812. tests := []struct {
  2813. param string
  2814. expected bool
  2815. }{
  2816. {"", true},
  2817. {"foobar", false},
  2818. {"xyz098", false},
  2819. {"123456", false},
  2820. {"カタカナ", false},
  2821. {"foobar", true},
  2822. {"0987654321", true},
  2823. {"test@example.com", true},
  2824. {"1234abcDEF", true},
  2825. {"newline\n", false},
  2826. {"\x19test\x7F", false},
  2827. }
  2828. validate := New()
  2829. for i, test := range tests {
  2830. errs := validate.Var(test.param, "printascii")
  2831. if test.expected {
  2832. if !IsEqual(errs, nil) {
  2833. t.Fatalf("Index: %d Printable ASCII failed Error: %s", i, errs)
  2834. }
  2835. } else {
  2836. if IsEqual(errs, nil) {
  2837. t.Fatalf("Index: %d Printable ASCII failed Error: %s", i, errs)
  2838. } else {
  2839. val := getError(errs, "", "")
  2840. if val.Tag() != "printascii" {
  2841. t.Fatalf("Index: %d Printable ASCII failed Error: %s", i, errs)
  2842. }
  2843. }
  2844. }
  2845. }
  2846. }
  2847. func TestASCIIValidation(t *testing.T) {
  2848. tests := []struct {
  2849. param string
  2850. expected bool
  2851. }{
  2852. {"", true},
  2853. {"foobar", false},
  2854. {"xyz098", false},
  2855. {"123456", false},
  2856. {"カタカナ", false},
  2857. {"foobar", true},
  2858. {"0987654321", true},
  2859. {"test@example.com", true},
  2860. {"1234abcDEF", true},
  2861. {"", true},
  2862. }
  2863. validate := New()
  2864. for i, test := range tests {
  2865. errs := validate.Var(test.param, "ascii")
  2866. if test.expected {
  2867. if !IsEqual(errs, nil) {
  2868. t.Fatalf("Index: %d ASCII failed Error: %s", i, errs)
  2869. }
  2870. } else {
  2871. if IsEqual(errs, nil) {
  2872. t.Fatalf("Index: %d ASCII failed Error: %s", i, errs)
  2873. } else {
  2874. val := getError(errs, "", "")
  2875. if val.Tag() != "ascii" {
  2876. t.Fatalf("Index: %d ASCII failed Error: %s", i, errs)
  2877. }
  2878. }
  2879. }
  2880. }
  2881. }
  2882. func TestUUID5Validation(t *testing.T) {
  2883. tests := []struct {
  2884. param string
  2885. expected bool
  2886. }{
  2887. {"", false},
  2888. {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
  2889. {"9c858901-8a57-4791-81fe-4c455b099bc9", false},
  2890. {"a987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
  2891. {"987fbc97-4bed-5078-af07-9141ba07c9f3", true},
  2892. {"987fbc97-4bed-5078-9f07-9141ba07c9f3", true},
  2893. }
  2894. validate := New()
  2895. for i, test := range tests {
  2896. errs := validate.Var(test.param, "uuid5")
  2897. if test.expected {
  2898. if !IsEqual(errs, nil) {
  2899. t.Fatalf("Index: %d UUID5 failed Error: %s", i, errs)
  2900. }
  2901. } else {
  2902. if IsEqual(errs, nil) {
  2903. t.Fatalf("Index: %d UUID5 failed Error: %s", i, errs)
  2904. } else {
  2905. val := getError(errs, "", "")
  2906. if val.Tag() != "uuid5" {
  2907. t.Fatalf("Index: %d UUID5 failed Error: %s", i, errs)
  2908. }
  2909. }
  2910. }
  2911. }
  2912. }
  2913. func TestUUID4Validation(t *testing.T) {
  2914. tests := []struct {
  2915. param string
  2916. expected bool
  2917. }{
  2918. {"", false},
  2919. {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
  2920. {"a987fbc9-4bed-5078-af07-9141ba07c9f3", false},
  2921. {"934859", false},
  2922. {"57b73598-8764-4ad0-a76a-679bb6640eb1", true},
  2923. {"625e63f3-58f5-40b7-83a1-a72ad31acffb", true},
  2924. }
  2925. validate := New()
  2926. for i, test := range tests {
  2927. errs := validate.Var(test.param, "uuid4")
  2928. if test.expected {
  2929. if !IsEqual(errs, nil) {
  2930. t.Fatalf("Index: %d UUID4 failed Error: %s", i, errs)
  2931. }
  2932. } else {
  2933. if IsEqual(errs, nil) {
  2934. t.Fatalf("Index: %d UUID4 failed Error: %s", i, errs)
  2935. } else {
  2936. val := getError(errs, "", "")
  2937. if val.Tag() != "uuid4" {
  2938. t.Fatalf("Index: %d UUID4 failed Error: %s", i, errs)
  2939. }
  2940. }
  2941. }
  2942. }
  2943. }
  2944. func TestUUID3Validation(t *testing.T) {
  2945. tests := []struct {
  2946. param string
  2947. expected bool
  2948. }{
  2949. {"", false},
  2950. {"412452646", false},
  2951. {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
  2952. {"a987fbc9-4bed-4078-8f07-9141ba07c9f3", false},
  2953. {"a987fbc9-4bed-3078-cf07-9141ba07c9f3", true},
  2954. }
  2955. validate := New()
  2956. for i, test := range tests {
  2957. errs := validate.Var(test.param, "uuid3")
  2958. if test.expected {
  2959. if !IsEqual(errs, nil) {
  2960. t.Fatalf("Index: %d UUID3 failed Error: %s", i, errs)
  2961. }
  2962. } else {
  2963. if IsEqual(errs, nil) {
  2964. t.Fatalf("Index: %d UUID3 failed Error: %s", i, errs)
  2965. } else {
  2966. val := getError(errs, "", "")
  2967. if val.Tag() != "uuid3" {
  2968. t.Fatalf("Index: %d UUID3 failed Error: %s", i, errs)
  2969. }
  2970. }
  2971. }
  2972. }
  2973. }
  2974. func TestUUIDValidation(t *testing.T) {
  2975. tests := []struct {
  2976. param string
  2977. expected bool
  2978. }{
  2979. {"", false},
  2980. {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9f3", false},
  2981. {"a987fbc9-4bed-3078-cf07-9141ba07c9f3xxx", false},
  2982. {"a987fbc94bed3078cf079141ba07c9f3", false},
  2983. {"934859", false},
  2984. {"987fbc9-4bed-3078-cf07a-9141ba07c9f3", false},
  2985. {"aaaaaaaa-1111-1111-aaag-111111111111", false},
  2986. {"a987fbc9-4bed-3078-cf07-9141ba07c9f3", true},
  2987. }
  2988. validate := New()
  2989. for i, test := range tests {
  2990. errs := validate.Var(test.param, "uuid")
  2991. if test.expected {
  2992. if !IsEqual(errs, nil) {
  2993. t.Fatalf("Index: %d UUID failed Error: %s", i, errs)
  2994. }
  2995. } else {
  2996. if IsEqual(errs, nil) {
  2997. t.Fatalf("Index: %d UUID failed Error: %s", i, errs)
  2998. } else {
  2999. val := getError(errs, "", "")
  3000. if val.Tag() != "uuid" {
  3001. t.Fatalf("Index: %d UUID failed Error: %s", i, errs)
  3002. }
  3003. }
  3004. }
  3005. }
  3006. }
  3007. func TestUUID5RFC4122Validation(t *testing.T) {
  3008. tests := []struct {
  3009. param string
  3010. expected bool
  3011. }{
  3012. {"", false},
  3013. {"xxxa987Fbc9-4bed-3078-cf07-9141ba07c9f3", false},
  3014. {"9c858901-8a57-4791-81Fe-4c455b099bc9", false},
  3015. {"a987Fbc9-4bed-3078-cf07-9141ba07c9f3", false},
  3016. {"987Fbc97-4bed-5078-af07-9141ba07c9f3", true},
  3017. {"987Fbc97-4bed-5078-9f07-9141ba07c9f3", true},
  3018. }
  3019. validate := New()
  3020. for i, test := range tests {
  3021. errs := validate.Var(test.param, "uuid5_rfc4122")
  3022. if test.expected {
  3023. if !IsEqual(errs, nil) {
  3024. t.Fatalf("Index: %d UUID5RFC4122 failed Error: %s", i, errs)
  3025. }
  3026. } else {
  3027. if IsEqual(errs, nil) {
  3028. t.Fatalf("Index: %d UUID5RFC4122 failed Error: %s", i, errs)
  3029. } else {
  3030. val := getError(errs, "", "")
  3031. if val.Tag() != "uuid5_rfc4122" {
  3032. t.Fatalf("Index: %d UUID5RFC4122 failed Error: %s", i, errs)
  3033. }
  3034. }
  3035. }
  3036. }
  3037. }
  3038. func TestUUID4RFC4122Validation(t *testing.T) {
  3039. tests := []struct {
  3040. param string
  3041. expected bool
  3042. }{
  3043. {"", false},
  3044. {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9F3", false},
  3045. {"a987fbc9-4bed-5078-af07-9141ba07c9F3", false},
  3046. {"934859", false},
  3047. {"57b73598-8764-4ad0-a76A-679bb6640eb1", true},
  3048. {"625e63f3-58f5-40b7-83a1-a72ad31acFfb", true},
  3049. }
  3050. validate := New()
  3051. for i, test := range tests {
  3052. errs := validate.Var(test.param, "uuid4_rfc4122")
  3053. if test.expected {
  3054. if !IsEqual(errs, nil) {
  3055. t.Fatalf("Index: %d UUID4RFC4122 failed Error: %s", i, errs)
  3056. }
  3057. } else {
  3058. if IsEqual(errs, nil) {
  3059. t.Fatalf("Index: %d UUID4RFC4122 failed Error: %s", i, errs)
  3060. } else {
  3061. val := getError(errs, "", "")
  3062. if val.Tag() != "uuid4_rfc4122" {
  3063. t.Fatalf("Index: %d UUID4RFC4122 failed Error: %s", i, errs)
  3064. }
  3065. }
  3066. }
  3067. }
  3068. }
  3069. func TestUUID3RFC4122Validation(t *testing.T) {
  3070. tests := []struct {
  3071. param string
  3072. expected bool
  3073. }{
  3074. {"", false},
  3075. {"412452646", false},
  3076. {"xxxa987fbc9-4bed-3078-cf07-9141ba07c9F3", false},
  3077. {"a987fbc9-4bed-4078-8f07-9141ba07c9F3", false},
  3078. {"a987fbc9-4bed-3078-cf07-9141ba07c9F3", true},
  3079. }
  3080. validate := New()
  3081. for i, test := range tests {
  3082. errs := validate.Var(test.param, "uuid3_rfc4122")
  3083. if test.expected {
  3084. if !IsEqual(errs, nil) {
  3085. t.Fatalf("Index: %d UUID3RFC4122 failed Error: %s", i, errs)
  3086. }
  3087. } else {
  3088. if IsEqual(errs, nil) {
  3089. t.Fatalf("Index: %d UUID3RFC4122 failed Error: %s", i, errs)
  3090. } else {
  3091. val := getError(errs, "", "")
  3092. if val.Tag() != "uuid3_rfc4122" {
  3093. t.Fatalf("Index: %d UUID3RFC4122 failed Error: %s", i, errs)
  3094. }
  3095. }
  3096. }
  3097. }
  3098. }
  3099. func TestUUIDRFC4122Validation(t *testing.T) {
  3100. tests := []struct {
  3101. param string
  3102. expected bool
  3103. }{
  3104. {"", false},
  3105. {"xxxa987Fbc9-4bed-3078-cf07-9141ba07c9f3", false},
  3106. {"a987Fbc9-4bed-3078-cf07-9141ba07c9f3xxx", false},
  3107. {"a987Fbc94bed3078cf079141ba07c9f3", false},
  3108. {"934859", false},
  3109. {"987fbc9-4bed-3078-cf07a-9141ba07c9F3", false},
  3110. {"aaaaaaaa-1111-1111-aaaG-111111111111", false},
  3111. {"a987Fbc9-4bed-3078-cf07-9141ba07c9f3", true},
  3112. }
  3113. validate := New()
  3114. for i, test := range tests {
  3115. errs := validate.Var(test.param, "uuid_rfc4122")
  3116. if test.expected {
  3117. if !IsEqual(errs, nil) {
  3118. t.Fatalf("Index: %d UUIDRFC4122 failed Error: %s", i, errs)
  3119. }
  3120. } else {
  3121. if IsEqual(errs, nil) {
  3122. t.Fatalf("Index: %d UUIDRFC4122 failed Error: %s", i, errs)
  3123. } else {
  3124. val := getError(errs, "", "")
  3125. if val.Tag() != "uuid_rfc4122" {
  3126. t.Fatalf("Index: %d UUIDRFC4122 failed Error: %s", i, errs)
  3127. }
  3128. }
  3129. }
  3130. }
  3131. }
  3132. func TestISBNValidation(t *testing.T) {
  3133. tests := []struct {
  3134. param string
  3135. expected bool
  3136. }{
  3137. {"", false},
  3138. {"foo", false},
  3139. {"3836221195", true},
  3140. {"1-61729-085-8", true},
  3141. {"3 423 21412 0", true},
  3142. {"3 401 01319 X", true},
  3143. {"9784873113685", true},
  3144. {"978-4-87311-368-5", true},
  3145. {"978 3401013190", true},
  3146. {"978-3-8362-2119-1", true},
  3147. }
  3148. validate := New()
  3149. for i, test := range tests {
  3150. errs := validate.Var(test.param, "isbn")
  3151. if test.expected {
  3152. if !IsEqual(errs, nil) {
  3153. t.Fatalf("Index: %d ISBN failed Error: %s", i, errs)
  3154. }
  3155. } else {
  3156. if IsEqual(errs, nil) {
  3157. t.Fatalf("Index: %d ISBN failed Error: %s", i, errs)
  3158. } else {
  3159. val := getError(errs, "", "")
  3160. if val.Tag() != "isbn" {
  3161. t.Fatalf("Index: %d ISBN failed Error: %s", i, errs)
  3162. }
  3163. }
  3164. }
  3165. }
  3166. }
  3167. func TestISBN13Validation(t *testing.T) {
  3168. tests := []struct {
  3169. param string
  3170. expected bool
  3171. }{
  3172. {"", false},
  3173. {"foo", false},
  3174. {"3-8362-2119-5", false},
  3175. {"01234567890ab", false},
  3176. {"978 3 8362 2119 0", false},
  3177. {"9784873113685", true},
  3178. {"978-4-87311-368-5", true},
  3179. {"978 3401013190", true},
  3180. {"978-3-8362-2119-1", true},
  3181. }
  3182. validate := New()
  3183. for i, test := range tests {
  3184. errs := validate.Var(test.param, "isbn13")
  3185. if test.expected {
  3186. if !IsEqual(errs, nil) {
  3187. t.Fatalf("Index: %d ISBN13 failed Error: %s", i, errs)
  3188. }
  3189. } else {
  3190. if IsEqual(errs, nil) {
  3191. t.Fatalf("Index: %d ISBN13 failed Error: %s", i, errs)
  3192. } else {
  3193. val := getError(errs, "", "")
  3194. if val.Tag() != "isbn13" {
  3195. t.Fatalf("Index: %d ISBN13 failed Error: %s", i, errs)
  3196. }
  3197. }
  3198. }
  3199. }
  3200. }
  3201. func TestISBN10Validation(t *testing.T) {
  3202. tests := []struct {
  3203. param string
  3204. expected bool
  3205. }{
  3206. {"", false},
  3207. {"foo", false},
  3208. {"3423214121", false},
  3209. {"978-3836221191", false},
  3210. {"3-423-21412-1", false},
  3211. {"3 423 21412 1", false},
  3212. {"3836221195", true},
  3213. {"1-61729-085-8", true},
  3214. {"3 423 21412 0", true},
  3215. {"3 401 01319 X", true},
  3216. }
  3217. validate := New()
  3218. for i, test := range tests {
  3219. errs := validate.Var(test.param, "isbn10")
  3220. if test.expected {
  3221. if !IsEqual(errs, nil) {
  3222. t.Fatalf("Index: %d ISBN10 failed Error: %s", i, errs)
  3223. }
  3224. } else {
  3225. if IsEqual(errs, nil) {
  3226. t.Fatalf("Index: %d ISBN10 failed Error: %s", i, errs)
  3227. } else {
  3228. val := getError(errs, "", "")
  3229. if val.Tag() != "isbn10" {
  3230. t.Fatalf("Index: %d ISBN10 failed Error: %s", i, errs)
  3231. }
  3232. }
  3233. }
  3234. }
  3235. }
  3236. func TestExcludesRuneValidation(t *testing.T) {
  3237. tests := []struct {
  3238. Value string `validate:"excludesrune=☻"`
  3239. Tag string
  3240. ExpectedNil bool
  3241. }{
  3242. {Value: "a☺b☻c☹d", Tag: "excludesrune=☻", ExpectedNil: false},
  3243. {Value: "abcd", Tag: "excludesrune=☻", ExpectedNil: true},
  3244. }
  3245. validate := New()
  3246. for i, s := range tests {
  3247. errs := validate.Var(s.Value, s.Tag)
  3248. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  3249. t.Fatalf("Index: %d failed Error: %s", i, errs)
  3250. }
  3251. errs = validate.Struct(s)
  3252. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  3253. t.Fatalf("Index: %d failed Error: %s", i, errs)
  3254. }
  3255. }
  3256. }
  3257. func TestExcludesAllValidation(t *testing.T) {
  3258. tests := []struct {
  3259. Value string `validate:"excludesall=@!{}[]"`
  3260. Tag string
  3261. ExpectedNil bool
  3262. }{
  3263. {Value: "abcd@!jfk", Tag: "excludesall=@!{}[]", ExpectedNil: false},
  3264. {Value: "abcdefg", Tag: "excludesall=@!{}[]", ExpectedNil: true},
  3265. }
  3266. validate := New()
  3267. for i, s := range tests {
  3268. errs := validate.Var(s.Value, s.Tag)
  3269. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  3270. t.Fatalf("Index: %d failed Error: %s", i, errs)
  3271. }
  3272. errs = validate.Struct(s)
  3273. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  3274. t.Fatalf("Index: %d failed Error: %s", i, errs)
  3275. }
  3276. }
  3277. username := "joeybloggs "
  3278. errs := validate.Var(username, "excludesall=@ ")
  3279. NotEqual(t, errs, nil)
  3280. AssertError(t, errs, "", "", "", "", "excludesall")
  3281. excluded := ","
  3282. errs = validate.Var(excluded, "excludesall=!@#$%^&*()_+.0x2C?")
  3283. NotEqual(t, errs, nil)
  3284. AssertError(t, errs, "", "", "", "", "excludesall")
  3285. excluded = "="
  3286. errs = validate.Var(excluded, "excludesall=!@#$%^&*()_+.0x2C=?")
  3287. NotEqual(t, errs, nil)
  3288. AssertError(t, errs, "", "", "", "", "excludesall")
  3289. }
  3290. func TestExcludesValidation(t *testing.T) {
  3291. tests := []struct {
  3292. Value string `validate:"excludes=@"`
  3293. Tag string
  3294. ExpectedNil bool
  3295. }{
  3296. {Value: "abcd@!jfk", Tag: "excludes=@", ExpectedNil: false},
  3297. {Value: "abcdq!jfk", Tag: "excludes=@", ExpectedNil: true},
  3298. }
  3299. validate := New()
  3300. for i, s := range tests {
  3301. errs := validate.Var(s.Value, s.Tag)
  3302. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  3303. t.Fatalf("Index: %d failed Error: %s", i, errs)
  3304. }
  3305. errs = validate.Struct(s)
  3306. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  3307. t.Fatalf("Index: %d failed Error: %s", i, errs)
  3308. }
  3309. }
  3310. }
  3311. func TestContainsRuneValidation(t *testing.T) {
  3312. tests := []struct {
  3313. Value string `validate:"containsrune=☻"`
  3314. Tag string
  3315. ExpectedNil bool
  3316. }{
  3317. {Value: "a☺b☻c☹d", Tag: "containsrune=☻", ExpectedNil: true},
  3318. {Value: "abcd", Tag: "containsrune=☻", ExpectedNil: false},
  3319. }
  3320. validate := New()
  3321. for i, s := range tests {
  3322. errs := validate.Var(s.Value, s.Tag)
  3323. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  3324. t.Fatalf("Index: %d failed Error: %s", i, errs)
  3325. }
  3326. errs = validate.Struct(s)
  3327. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  3328. t.Fatalf("Index: %d failed Error: %s", i, errs)
  3329. }
  3330. }
  3331. }
  3332. func TestContainsAnyValidation(t *testing.T) {
  3333. tests := []struct {
  3334. Value string `validate:"containsany=@!{}[]"`
  3335. Tag string
  3336. ExpectedNil bool
  3337. }{
  3338. {Value: "abcd@!jfk", Tag: "containsany=@!{}[]", ExpectedNil: true},
  3339. {Value: "abcdefg", Tag: "containsany=@!{}[]", ExpectedNil: false},
  3340. }
  3341. validate := New()
  3342. for i, s := range tests {
  3343. errs := validate.Var(s.Value, s.Tag)
  3344. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  3345. t.Fatalf("Index: %d failed Error: %s", i, errs)
  3346. }
  3347. errs = validate.Struct(s)
  3348. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  3349. t.Fatalf("Index: %d failed Error: %s", i, errs)
  3350. }
  3351. }
  3352. }
  3353. func TestContainsValidation(t *testing.T) {
  3354. tests := []struct {
  3355. Value string `validate:"contains=@"`
  3356. Tag string
  3357. ExpectedNil bool
  3358. }{
  3359. {Value: "abcd@!jfk", Tag: "contains=@", ExpectedNil: true},
  3360. {Value: "abcdq!jfk", Tag: "contains=@", ExpectedNil: false},
  3361. }
  3362. validate := New()
  3363. for i, s := range tests {
  3364. errs := validate.Var(s.Value, s.Tag)
  3365. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  3366. t.Fatalf("Index: %d failed Error: %s", i, errs)
  3367. }
  3368. errs = validate.Struct(s)
  3369. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  3370. t.Fatalf("Index: %d failed Error: %s", i, errs)
  3371. }
  3372. }
  3373. }
  3374. func TestIsNeFieldValidation(t *testing.T) {
  3375. validate := New()
  3376. var j uint64
  3377. var k float64
  3378. s := "abcd"
  3379. i := 1
  3380. j = 1
  3381. k = 1.543
  3382. arr := []string{"test"}
  3383. now := time.Now().UTC()
  3384. var j2 uint64
  3385. var k2 float64
  3386. s2 := "abcdef"
  3387. i2 := 3
  3388. j2 = 2
  3389. k2 = 1.5434456
  3390. arr2 := []string{"test", "test2"}
  3391. arr3 := []string{"test"}
  3392. now2 := now
  3393. errs := validate.VarWithValue(s, s2, "nefield")
  3394. Equal(t, errs, nil)
  3395. errs = validate.VarWithValue(i2, i, "nefield")
  3396. Equal(t, errs, nil)
  3397. errs = validate.VarWithValue(j2, j, "nefield")
  3398. Equal(t, errs, nil)
  3399. errs = validate.VarWithValue(k2, k, "nefield")
  3400. Equal(t, errs, nil)
  3401. errs = validate.VarWithValue(arr2, arr, "nefield")
  3402. Equal(t, errs, nil)
  3403. errs = validate.VarWithValue(now2, now, "nefield")
  3404. NotEqual(t, errs, nil)
  3405. AssertError(t, errs, "", "", "", "", "nefield")
  3406. errs = validate.VarWithValue(arr3, arr, "nefield")
  3407. NotEqual(t, errs, nil)
  3408. AssertError(t, errs, "", "", "", "", "nefield")
  3409. type Test struct {
  3410. Start *time.Time `validate:"nefield=End"`
  3411. End *time.Time
  3412. }
  3413. sv := &Test{
  3414. Start: &now,
  3415. End: &now,
  3416. }
  3417. errs = validate.Struct(sv)
  3418. NotEqual(t, errs, nil)
  3419. AssertError(t, errs, "Test.Start", "Test.Start", "Start", "Start", "nefield")
  3420. now3 := time.Now().UTC()
  3421. sv = &Test{
  3422. Start: &now,
  3423. End: &now3,
  3424. }
  3425. errs = validate.Struct(sv)
  3426. Equal(t, errs, nil)
  3427. errs = validate.VarWithValue(nil, 1, "nefield")
  3428. NotEqual(t, errs, nil)
  3429. AssertError(t, errs, "", "", "", "", "nefield")
  3430. errs = validate.VarWithValue(sv, now, "nefield")
  3431. Equal(t, errs, nil)
  3432. type Test2 struct {
  3433. Start *time.Time `validate:"nefield=NonExistantField"`
  3434. End *time.Time
  3435. }
  3436. sv2 := &Test2{
  3437. Start: &now,
  3438. End: &now,
  3439. }
  3440. errs = validate.Struct(sv2)
  3441. Equal(t, errs, nil)
  3442. type Other struct {
  3443. Value string
  3444. }
  3445. type Test3 struct {
  3446. Value Other
  3447. Time time.Time `validate:"nefield=Value"`
  3448. }
  3449. tst := Test3{
  3450. Value: Other{Value: "StringVal"},
  3451. Time: now,
  3452. }
  3453. errs = validate.Struct(tst)
  3454. Equal(t, errs, nil)
  3455. }
  3456. func TestIsNeValidation(t *testing.T) {
  3457. validate := New()
  3458. var j uint64
  3459. var k float64
  3460. s := "abcdef"
  3461. i := 3
  3462. j = 2
  3463. k = 1.5434
  3464. arr := []string{"test"}
  3465. now := time.Now().UTC()
  3466. errs := validate.Var(s, "ne=abcd")
  3467. Equal(t, errs, nil)
  3468. errs = validate.Var(i, "ne=1")
  3469. Equal(t, errs, nil)
  3470. errs = validate.Var(j, "ne=1")
  3471. Equal(t, errs, nil)
  3472. errs = validate.Var(k, "ne=1.543")
  3473. Equal(t, errs, nil)
  3474. errs = validate.Var(arr, "ne=2")
  3475. Equal(t, errs, nil)
  3476. errs = validate.Var(arr, "ne=1")
  3477. NotEqual(t, errs, nil)
  3478. AssertError(t, errs, "", "", "", "", "ne")
  3479. PanicMatches(t, func() { validate.Var(now, "ne=now") }, "Bad field type time.Time")
  3480. }
  3481. func TestIsEqFieldValidation(t *testing.T) {
  3482. validate := New()
  3483. var j uint64
  3484. var k float64
  3485. s := "abcd"
  3486. i := 1
  3487. j = 1
  3488. k = 1.543
  3489. arr := []string{"test"}
  3490. now := time.Now().UTC()
  3491. var j2 uint64
  3492. var k2 float64
  3493. s2 := "abcd"
  3494. i2 := 1
  3495. j2 = 1
  3496. k2 = 1.543
  3497. arr2 := []string{"test"}
  3498. arr3 := []string{"test", "test2"}
  3499. now2 := now
  3500. errs := validate.VarWithValue(s, s2, "eqfield")
  3501. Equal(t, errs, nil)
  3502. errs = validate.VarWithValue(i2, i, "eqfield")
  3503. Equal(t, errs, nil)
  3504. errs = validate.VarWithValue(j2, j, "eqfield")
  3505. Equal(t, errs, nil)
  3506. errs = validate.VarWithValue(k2, k, "eqfield")
  3507. Equal(t, errs, nil)
  3508. errs = validate.VarWithValue(arr2, arr, "eqfield")
  3509. Equal(t, errs, nil)
  3510. errs = validate.VarWithValue(now2, now, "eqfield")
  3511. Equal(t, errs, nil)
  3512. errs = validate.VarWithValue(arr3, arr, "eqfield")
  3513. NotEqual(t, errs, nil)
  3514. AssertError(t, errs, "", "", "", "", "eqfield")
  3515. type Test struct {
  3516. Start *time.Time `validate:"eqfield=End"`
  3517. End *time.Time
  3518. }
  3519. sv := &Test{
  3520. Start: &now,
  3521. End: &now,
  3522. }
  3523. errs = validate.Struct(sv)
  3524. Equal(t, errs, nil)
  3525. now3 := time.Now().UTC()
  3526. sv = &Test{
  3527. Start: &now,
  3528. End: &now3,
  3529. }
  3530. errs = validate.Struct(sv)
  3531. NotEqual(t, errs, nil)
  3532. AssertError(t, errs, "Test.Start", "Test.Start", "Start", "Start", "eqfield")
  3533. errs = validate.VarWithValue(nil, 1, "eqfield")
  3534. NotEqual(t, errs, nil)
  3535. AssertError(t, errs, "", "", "", "", "eqfield")
  3536. channel := make(chan string)
  3537. errs = validate.VarWithValue(5, channel, "eqfield")
  3538. NotEqual(t, errs, nil)
  3539. AssertError(t, errs, "", "", "", "", "eqfield")
  3540. errs = validate.VarWithValue(5, now, "eqfield")
  3541. NotEqual(t, errs, nil)
  3542. AssertError(t, errs, "", "", "", "", "eqfield")
  3543. type Test2 struct {
  3544. Start *time.Time `validate:"eqfield=NonExistantField"`
  3545. End *time.Time
  3546. }
  3547. sv2 := &Test2{
  3548. Start: &now,
  3549. End: &now,
  3550. }
  3551. errs = validate.Struct(sv2)
  3552. NotEqual(t, errs, nil)
  3553. AssertError(t, errs, "Test2.Start", "Test2.Start", "Start", "Start", "eqfield")
  3554. type Inner struct {
  3555. Name string
  3556. }
  3557. type TStruct struct {
  3558. Inner *Inner
  3559. CreatedAt *time.Time `validate:"eqfield=Inner"`
  3560. }
  3561. inner := &Inner{
  3562. Name: "NAME",
  3563. }
  3564. test := &TStruct{
  3565. Inner: inner,
  3566. CreatedAt: &now,
  3567. }
  3568. errs = validate.Struct(test)
  3569. NotEqual(t, errs, nil)
  3570. AssertError(t, errs, "TStruct.CreatedAt", "TStruct.CreatedAt", "CreatedAt", "CreatedAt", "eqfield")
  3571. }
  3572. func TestIsEqValidation(t *testing.T) {
  3573. validate := New()
  3574. var j uint64
  3575. var k float64
  3576. s := "abcd"
  3577. i := 1
  3578. j = 1
  3579. k = 1.543
  3580. arr := []string{"test"}
  3581. now := time.Now().UTC()
  3582. errs := validate.Var(s, "eq=abcd")
  3583. Equal(t, errs, nil)
  3584. errs = validate.Var(i, "eq=1")
  3585. Equal(t, errs, nil)
  3586. errs = validate.Var(j, "eq=1")
  3587. Equal(t, errs, nil)
  3588. errs = validate.Var(k, "eq=1.543")
  3589. Equal(t, errs, nil)
  3590. errs = validate.Var(arr, "eq=1")
  3591. Equal(t, errs, nil)
  3592. errs = validate.Var(arr, "eq=2")
  3593. NotEqual(t, errs, nil)
  3594. AssertError(t, errs, "", "", "", "", "eq")
  3595. PanicMatches(t, func() { validate.Var(now, "eq=now") }, "Bad field type time.Time")
  3596. }
  3597. func TestOneOfValidation(t *testing.T) {
  3598. validate := New()
  3599. passSpecs := []struct {
  3600. f interface{}
  3601. t string
  3602. }{
  3603. {f: "red", t: "oneof=red green"},
  3604. {f: "green", t: "oneof=red green"},
  3605. {f: 5, t: "oneof=5 6"},
  3606. {f: 6, t: "oneof=5 6"},
  3607. {f: int8(6), t: "oneof=5 6"},
  3608. {f: int16(6), t: "oneof=5 6"},
  3609. {f: int32(6), t: "oneof=5 6"},
  3610. {f: int64(6), t: "oneof=5 6"},
  3611. {f: uint(6), t: "oneof=5 6"},
  3612. {f: uint8(6), t: "oneof=5 6"},
  3613. {f: uint16(6), t: "oneof=5 6"},
  3614. {f: uint32(6), t: "oneof=5 6"},
  3615. {f: uint64(6), t: "oneof=5 6"},
  3616. }
  3617. for _, spec := range passSpecs {
  3618. t.Logf("%#v", spec)
  3619. errs := validate.Var(spec.f, spec.t)
  3620. Equal(t, errs, nil)
  3621. }
  3622. failSpecs := []struct {
  3623. f interface{}
  3624. t string
  3625. }{
  3626. {f: "", t: "oneof=red green"},
  3627. {f: "yellow", t: "oneof=red green"},
  3628. {f: 5, t: "oneof=red green"},
  3629. {f: 6, t: "oneof=red green"},
  3630. {f: 6, t: "oneof=7"},
  3631. {f: uint(6), t: "oneof=7"},
  3632. {f: int8(5), t: "oneof=red green"},
  3633. {f: int16(5), t: "oneof=red green"},
  3634. {f: int32(5), t: "oneof=red green"},
  3635. {f: int64(5), t: "oneof=red green"},
  3636. {f: uint(5), t: "oneof=red green"},
  3637. {f: uint8(5), t: "oneof=red green"},
  3638. {f: uint16(5), t: "oneof=red green"},
  3639. {f: uint32(5), t: "oneof=red green"},
  3640. {f: uint64(5), t: "oneof=red green"},
  3641. }
  3642. for _, spec := range failSpecs {
  3643. t.Logf("%#v", spec)
  3644. errs := validate.Var(spec.f, spec.t)
  3645. AssertError(t, errs, "", "", "", "", "oneof")
  3646. }
  3647. PanicMatches(t, func() {
  3648. validate.Var(3.14, "oneof=red green")
  3649. }, "Bad field type float64")
  3650. }
  3651. func TestBase64Validation(t *testing.T) {
  3652. validate := New()
  3653. s := "dW5pY29ybg=="
  3654. errs := validate.Var(s, "base64")
  3655. Equal(t, errs, nil)
  3656. s = "dGhpIGlzIGEgdGVzdCBiYXNlNjQ="
  3657. errs = validate.Var(s, "base64")
  3658. Equal(t, errs, nil)
  3659. s = ""
  3660. errs = validate.Var(s, "base64")
  3661. NotEqual(t, errs, nil)
  3662. AssertError(t, errs, "", "", "", "", "base64")
  3663. s = "dW5pY29ybg== foo bar"
  3664. errs = validate.Var(s, "base64")
  3665. NotEqual(t, errs, nil)
  3666. AssertError(t, errs, "", "", "", "", "base64")
  3667. }
  3668. func TestBase64URLValidation(t *testing.T) {
  3669. validate := New()
  3670. testCases := []struct {
  3671. decoded, encoded string
  3672. success bool
  3673. }{
  3674. // empty string, although a valid base64 string, should fail
  3675. {"", "", false},
  3676. // invalid length
  3677. {"", "a", false},
  3678. // base64 with padding
  3679. {"f", "Zg==", true},
  3680. {"fo", "Zm8=", true},
  3681. // base64 without padding
  3682. {"foo", "Zm9v", true},
  3683. {"", "Zg", false},
  3684. {"", "Zm8", false},
  3685. // base64 URL safe encoding with invalid, special characters '+' and '/'
  3686. {"\x14\xfb\x9c\x03\xd9\x7e", "FPucA9l+", false},
  3687. {"\x14\xfb\x9c\x03\xf9\x73", "FPucA/lz", false},
  3688. // base64 URL safe encoding with valid, special characters '-' and '_'
  3689. {"\x14\xfb\x9c\x03\xd9\x7e", "FPucA9l-", true},
  3690. {"\x14\xfb\x9c\x03\xf9\x73", "FPucA_lz", true},
  3691. // non base64 characters
  3692. {"", "@mc=", false},
  3693. {"", "Zm 9", false},
  3694. }
  3695. for _, tc := range testCases {
  3696. err := validate.Var(tc.encoded, "base64url")
  3697. if tc.success {
  3698. Equal(t, err, nil)
  3699. // make sure encoded value is decoded back to the expected value
  3700. d, innerErr := base64.URLEncoding.DecodeString(tc.encoded)
  3701. Equal(t, innerErr, nil)
  3702. Equal(t, tc.decoded, string(d))
  3703. } else {
  3704. NotEqual(t, err, nil)
  3705. if len(tc.encoded) > 0 {
  3706. // make sure that indeed the encoded value was faulty
  3707. _, err := base64.URLEncoding.DecodeString(tc.encoded)
  3708. NotEqual(t, err, nil)
  3709. }
  3710. }
  3711. }
  3712. }
  3713. func TestFileValidation(t *testing.T) {
  3714. validate := New()
  3715. tests := []struct {
  3716. title string
  3717. param string
  3718. expected bool
  3719. }{
  3720. {"empty path", "", false},
  3721. {"regular file", filepath.Join("testdata", "a.go"), true},
  3722. {"missing file", filepath.Join("testdata", "no.go"), false},
  3723. {"directory, not a file", "testdata", false},
  3724. }
  3725. for _, test := range tests {
  3726. errs := validate.Var(test.param, "file")
  3727. if test.expected {
  3728. if !IsEqual(errs, nil) {
  3729. t.Fatalf("Test: '%s' failed Error: %s", test.title, errs)
  3730. }
  3731. } else {
  3732. if IsEqual(errs, nil) {
  3733. t.Fatalf("Test: '%s' failed Error: %s", test.title, errs)
  3734. }
  3735. }
  3736. }
  3737. PanicMatches(t, func() {
  3738. validate.Var(6, "file")
  3739. }, "Bad field type int")
  3740. }
  3741. func TestEthereumAddressValidation(t *testing.T) {
  3742. validate := New()
  3743. tests := []struct {
  3744. param string
  3745. expected bool
  3746. }{
  3747. {"", false},
  3748. {"0x02F9AE5f22EA3fA88F05780B30385bEC", false},
  3749. {"123f681646d4a755815f9cb19e1acc8565a0c2ac", false},
  3750. {"0x02F9AE5f22EA3fA88F05780B30385bECFacbf130", true},
  3751. {"0x123f681646d4a755815f9cb19e1acc8565a0c2ac", true},
  3752. }
  3753. for i, test := range tests {
  3754. errs := validate.Var(test.param, "eth_addr")
  3755. if test.expected {
  3756. if !IsEqual(errs, nil) {
  3757. t.Fatalf("Index: %d eth_addr failed Error: %s", i, errs)
  3758. }
  3759. } else {
  3760. if IsEqual(errs, nil) {
  3761. t.Fatalf("Index: %d eth_addr failed Error: %s", i, errs)
  3762. } else {
  3763. val := getError(errs, "", "")
  3764. if val.Tag() != "eth_addr" {
  3765. t.Fatalf("Index: %d Latitude failed Error: %s", i, errs)
  3766. }
  3767. }
  3768. }
  3769. }
  3770. }
  3771. func TestBitcoinAddressValidation(t *testing.T) {
  3772. validate := New()
  3773. tests := []struct {
  3774. param string
  3775. expected bool
  3776. }{
  3777. {"", false},
  3778. {"x", false},
  3779. {"0x02F9AE5f22EA3fA88F05780B30385bEC", false},
  3780. {"1A1zP1ePQGefi2DMPTifTL5SLmv7DivfNa", false},
  3781. {"1P9RQEr2XeE3PEb44ZE35sfZRRW1JH8Uqx", false},
  3782. {"3P14159I73E4gFr7JterCCQh9QjiTjiZrG", false},
  3783. {"3P141597f3E4gFr7JterCCQh9QjiTjiZrG", false},
  3784. {"37qgekLpCCHrQuSjvX3fs496FWTGsHFHizjJAs6NPcR47aefnnCWECAhHV6E3g4YN7u7Yuwod5Y", false},
  3785. {"dzb7VV1Ui55BARxv7ATxAtCUeJsANKovDGWFVgpTbhq9gvPqP3yv", false},
  3786. {"MuNu7ZAEDFiHthiunm7dPjwKqrVNCM3mAz6rP9zFveQu14YA8CxExSJTHcVP9DErn6u84E6Ej7S", false},
  3787. {"rPpQpYknyNQ5AEHuY6H8ijJJrYc2nDKKk9jjmKEXsWzyAQcFGpDLU2Zvsmoi8JLR7hAwoy3RQWf", false},
  3788. {"4Uc3FmN6NQ6zLBK5QQBXRBUREaaHwCZYsGCueHauuDmJpZKn6jkEskMB2Zi2CNgtb5r6epWEFfUJq", false},
  3789. {"7aQgR5DFQ25vyXmqZAWmnVCjL3PkBcdVkBUpjrjMTcghHx3E8wb", false},
  3790. {"17QpPprjeg69fW1DV8DcYYCKvWjYhXvWkov6MJ1iTTvMFj6weAqW7wybZeH57WTNxXVCRH4veVs", false},
  3791. {"KxuACDviz8Xvpn1xAh9MfopySZNuyajYMZWz16Dv2mHHryznWUp3", false},
  3792. {"7nK3GSmqdXJQtdohvGfJ7KsSmn3TmGqExug49583bDAL91pVSGq5xS9SHoAYL3Wv3ijKTit65th", false},
  3793. {"cTivdBmq7bay3RFGEBBuNfMh2P1pDCgRYN2Wbxmgwr4ki3jNUL2va", false},
  3794. {"gjMV4vjNjyMrna4fsAr8bWxAbwtmMUBXJS3zL4NJt5qjozpbQLmAfK1uA3CquSqsZQMpoD1g2nk", false},
  3795. {"emXm1naBMoVzPjbk7xpeTVMFy4oDEe25UmoyGgKEB1gGWsK8kRGs", false},
  3796. {"7VThQnNRj1o3Zyvc7XHPRrjDf8j2oivPTeDXnRPYWeYGE4pXeRJDZgf28ppti5hsHWXS2GSobdqyo", false},
  3797. {"1G9u6oCVCPh2o8m3t55ACiYvG1y5BHewUkDSdiQarDcYXXhFHYdzMdYfUAhfxn5vNZBwpgUNpso", false},
  3798. {"31QQ7ZMLkScDiB4VyZjuptr7AEc9j1SjstF7pRoLhHTGkW4Q2y9XELobQmhhWxeRvqcukGd1XCq", false},
  3799. {"DHqKSnpxa8ZdQyH8keAhvLTrfkyBMQxqngcQA5N8LQ9KVt25kmGN", false},
  3800. {"2LUHcJPbwLCy9GLH1qXmfmAwvadWw4bp4PCpDfduLqV17s6iDcy1imUwhQJhAoNoN1XNmweiJP4i", false},
  3801. {"7USRzBXAnmck8fX9HmW7RAb4qt92VFX6soCnts9s74wxm4gguVhtG5of8fZGbNPJA83irHVY6bCos", false},
  3802. {"1DGezo7BfVebZxAbNT3XGujdeHyNNBF3vnficYoTSp4PfK2QaML9bHzAMxke3wdKdHYWmsMTJVu", false},
  3803. {"2D12DqDZKwCxxkzs1ZATJWvgJGhQ4cFi3WrizQ5zLAyhN5HxuAJ1yMYaJp8GuYsTLLxTAz6otCfb", false},
  3804. {"8AFJzuTujXjw1Z6M3fWhQ1ujDW7zsV4ePeVjVo7D1egERqSW9nZ", false},
  3805. {"163Q17qLbTCue8YY3AvjpUhotuaodLm2uqMhpYirsKjVqnxJRWTEoywMVY3NbBAHuhAJ2cF9GAZ", false},
  3806. {"2MnmgiRH4eGLyLc9eAqStzk7dFgBjFtUCtu", false},
  3807. {"461QQ2sYWxU7H2PV4oBwJGNch8XVTYYbZxU", false},
  3808. {"2UCtv53VttmQYkVU4VMtXB31REvQg4ABzs41AEKZ8UcB7DAfVzdkV9JDErwGwyj5AUHLkmgZeobs", false},
  3809. {"cSNjAsnhgtiFMi6MtfvgscMB2Cbhn2v1FUYfviJ1CdjfidvmeW6mn", false},
  3810. {"gmsow2Y6EWAFDFE1CE4Hd3Tpu2BvfmBfG1SXsuRARbnt1WjkZnFh1qGTiptWWbjsq2Q6qvpgJVj", false},
  3811. {"nksUKSkzS76v8EsSgozXGMoQFiCoCHzCVajFKAXqzK5on9ZJYVHMD5CKwgmX3S3c7M1U3xabUny", false},
  3812. {"L3favK1UzFGgdzYBF2oBT5tbayCo4vtVBLJhg2iYuMeePxWG8SQc", false},
  3813. {"7VxLxGGtYT6N99GdEfi6xz56xdQ8nP2dG1CavuXx7Rf2PrvNMTBNevjkfgs9JmkcGm6EXpj8ipyPZ ", false},
  3814. {"2mbZwFXF6cxShaCo2czTRB62WTx9LxhTtpP", false},
  3815. {"dB7cwYdcPSgiyAwKWL3JwCVwSk6epU2txw", false},
  3816. {"HPhFUhUAh8ZQQisH8QQWafAxtQYju3SFTX", false},
  3817. {"4ctAH6AkHzq5ioiM1m9T3E2hiYEev5mTsB", false},
  3818. {"31uEbMgunupShBVTewXjtqbBv5MndwfXhb", false},
  3819. {"175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W", false},
  3820. {"Hn1uFi4dNexWrqARpjMqgT6cX1UsNPuV3cHdGg9ExyXw8HTKadbktRDtdeVmY3M1BxJStiL4vjJ", false},
  3821. {"Sq3fDbvutABmnAHHExJDgPLQn44KnNC7UsXuT7KZecpaYDMU9Txs", false},
  3822. {"6TqWyrqdgUEYDQU1aChMuFMMEimHX44qHFzCUgGfqxGgZNMUVWJ", false},
  3823. {"giqJo7oWqFxNKWyrgcBxAVHXnjJ1t6cGoEffce5Y1y7u649Noj5wJ4mmiUAKEVVrYAGg2KPB3Y4", false},
  3824. {"cNzHY5e8vcmM3QVJUcjCyiKMYfeYvyueq5qCMV3kqcySoLyGLYUK", false},
  3825. {"37uTe568EYc9WLoHEd9jXEvUiWbq5LFLscNyqvAzLU5vBArUJA6eydkLmnMwJDjkL5kXc2VK7ig", false},
  3826. {"EsYbG4tWWWY45G31nox838qNdzksbPySWc", false},
  3827. {"nbuzhfwMoNzA3PaFnyLcRxE9bTJPDkjZ6Rf6Y6o2ckXZfzZzXBT", false},
  3828. {"cQN9PoxZeCWK1x56xnz6QYAsvR11XAce3Ehp3gMUdfSQ53Y2mPzx", false},
  3829. {"1Gm3N3rkef6iMbx4voBzaxtXcmmiMTqZPhcuAepRzYUJQW4qRpEnHvMojzof42hjFRf8PE2jPde", false},
  3830. {"2TAq2tuN6x6m233bpT7yqdYQPELdTDJn1eU", false},
  3831. {"ntEtnnGhqPii4joABvBtSEJG6BxjT2tUZqE8PcVYgk3RHpgxgHDCQxNbLJf7ardf1dDk2oCQ7Cf", false},
  3832. {"Ky1YjoZNgQ196HJV3HpdkecfhRBmRZdMJk89Hi5KGfpfPwS2bUbfd", false},
  3833. {"2A1q1YsMZowabbvta7kTy2Fd6qN4r5ZCeG3qLpvZBMzCixMUdkN2Y4dHB1wPsZAeVXUGD83MfRED", false},
  3834. {"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", true},
  3835. {"1Ax4gZtb7gAit2TivwejZHYtNNLT18PUXJ", true},
  3836. {"1C5bSj1iEGUgSTbziymG7Cn18ENQuT36vv", true},
  3837. {"1Gqk4Tv79P91Cc1STQtU3s1W6277M2CVWu", true},
  3838. {"1JwMWBVLtiqtscbaRHai4pqHokhFCbtoB4", true},
  3839. {"19dcawoKcZdQz365WpXWMhX6QCUpR9SY4r", true},
  3840. {"13p1ijLwsnrcuyqcTvJXkq2ASdXqcnEBLE", true},
  3841. {"1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2", true},
  3842. {"3P14159f73E4gFr7JterCCQh9QjiTjiZrG", true},
  3843. {"3CMNFxN1oHBc4R1EpboAL5yzHGgE611Xou", true},
  3844. {"3QjYXhTkvuj8qPaXHTTWb5wjXhdsLAAWVy", true},
  3845. {"3AnNxabYGoTxYiTEZwFEnerUoeFXK2Zoks", true},
  3846. {"33vt8ViH5jsr115AGkW6cEmEz9MpvJSwDk", true},
  3847. {"3QCzvfL4ZRvmJFiWWBVwxfdaNBT8EtxB5y", true},
  3848. {"37Sp6Rv3y4kVd1nQ1JV5pfqXccHNyZm1x3", true},
  3849. {"3ALJH9Y951VCGcVZYAdpA3KchoP9McEj1G", true},
  3850. {"12KYrjTdVGjFMtaxERSk3gphreJ5US8aUP", true},
  3851. {"12QeMLzSrB8XH8FvEzPMVoRxVAzTr5XM2y", true},
  3852. {"1oNLrsHnBcR6dpaBpwz3LSwutbUNkNSjs", true},
  3853. {"1SQHtwR5oJRKLfiWQ2APsAd9miUc4k2ez", true},
  3854. {"116CGDLddrZhMrTwhCVJXtXQpxygTT1kHd", true},
  3855. {"3NJZLcZEEYBpxYEUGewU4knsQRn1WM5Fkt", true},
  3856. }
  3857. for i, test := range tests {
  3858. errs := validate.Var(test.param, "btc_addr")
  3859. if test.expected {
  3860. if !IsEqual(errs, nil) {
  3861. t.Fatalf("Index: %d btc_addr failed with Error: %s", i, errs)
  3862. }
  3863. } else {
  3864. if IsEqual(errs, nil) {
  3865. t.Fatalf("Index: %d btc_addr failed with Error: %s", i, errs)
  3866. } else {
  3867. val := getError(errs, "", "")
  3868. if val.Tag() != "btc_addr" {
  3869. t.Fatalf("Index: %d Latitude failed with Error: %s", i, errs)
  3870. }
  3871. }
  3872. }
  3873. }
  3874. }
  3875. func TestBitcoinBech32AddressValidation(t *testing.T) {
  3876. validate := New()
  3877. tests := []struct {
  3878. param string
  3879. expected bool
  3880. }{
  3881. {"", false},
  3882. {"bc1rw5uspcuh", false},
  3883. {"bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t5", false},
  3884. {"BC13W508D6QEJXTDG4Y5R3ZARVARY0C5XW7KN40WF2", false},
  3885. {"qw508d6qejxtdg4y5r3zarvary0c5xw7kg3g4ty", false},
  3886. {"bc1rw5uspcuh", false},
  3887. {"bc10w508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kw5rljs90", false},
  3888. {"BC1QW508d6QEJxTDG4y5R3ZArVARY0C5XW7KV8F3T4", false},
  3889. {"BC1QR508D6QEJXTDG4Y5R3ZARVARYV98GJ9P", false},
  3890. {"bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t5", false},
  3891. {"bc10w508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7kw5rljs90", false},
  3892. {"bc1pw508d6qejxtdg4y5r3zarqfsj6c3", false},
  3893. {"bc1zw508d6qejxtdg4y5r3zarvaryvqyzf3du", false},
  3894. {"bc1gmk9yu", false},
  3895. {"bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3pjxtptv", false},
  3896. {"BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4", true},
  3897. {"bc1pw508d6qejxtdg4y5r3zarvary0c5xw7kw508d6qejxtdg4y5r3zarvary0c5xw7k7grplx", true},
  3898. {"bc1qrp33g0q5c5txsp9arysrx4k6zdkfs4nce4xj0gdcccefvpysxf3qccfmv3", true},
  3899. {"BC1SW50QA3JX3S", true},
  3900. {"bc1zw508d6qejxtdg4y5r3zarvaryvg6kdaj", true},
  3901. }
  3902. for i, test := range tests {
  3903. errs := validate.Var(test.param, "btc_addr_bech32")
  3904. if test.expected {
  3905. if !IsEqual(errs, nil) {
  3906. t.Fatalf("Index: %d btc_addr_bech32 failed with Error: %s", i, errs)
  3907. }
  3908. } else {
  3909. if IsEqual(errs, nil) {
  3910. t.Fatalf("Index: %d btc_addr_bech32 failed with Error: %s", i, errs)
  3911. } else {
  3912. val := getError(errs, "", "")
  3913. if val.Tag() != "btc_addr_bech32" {
  3914. t.Fatalf("Index: %d Latitude failed with Error: %s", i, errs)
  3915. }
  3916. }
  3917. }
  3918. }
  3919. }
  3920. func TestNoStructLevelValidation(t *testing.T) {
  3921. type Inner struct {
  3922. Test string `validate:"len=5"`
  3923. }
  3924. type Outer struct {
  3925. InnerStruct *Inner `validate:"required,nostructlevel"`
  3926. }
  3927. outer := &Outer{
  3928. InnerStruct: nil,
  3929. }
  3930. validate := New()
  3931. errs := validate.Struct(outer)
  3932. NotEqual(t, errs, nil)
  3933. AssertError(t, errs, "Outer.InnerStruct", "Outer.InnerStruct", "InnerStruct", "InnerStruct", "required")
  3934. inner := &Inner{
  3935. Test: "1234",
  3936. }
  3937. outer = &Outer{
  3938. InnerStruct: inner,
  3939. }
  3940. errs = validate.Struct(outer)
  3941. Equal(t, errs, nil)
  3942. }
  3943. func TestStructOnlyValidation(t *testing.T) {
  3944. type Inner struct {
  3945. Test string `validate:"len=5"`
  3946. }
  3947. type Outer struct {
  3948. InnerStruct *Inner `validate:"required,structonly"`
  3949. }
  3950. outer := &Outer{
  3951. InnerStruct: nil,
  3952. }
  3953. validate := New()
  3954. errs := validate.Struct(outer)
  3955. NotEqual(t, errs, nil)
  3956. AssertError(t, errs, "Outer.InnerStruct", "Outer.InnerStruct", "InnerStruct", "InnerStruct", "required")
  3957. inner := &Inner{
  3958. Test: "1234",
  3959. }
  3960. outer = &Outer{
  3961. InnerStruct: inner,
  3962. }
  3963. errs = validate.Struct(outer)
  3964. Equal(t, errs, nil)
  3965. // Address houses a users address information
  3966. type Address struct {
  3967. Street string `validate:"required"`
  3968. City string `validate:"required"`
  3969. Planet string `validate:"required"`
  3970. Phone string `validate:"required"`
  3971. }
  3972. type User struct {
  3973. FirstName string `json:"fname"`
  3974. LastName string `json:"lname"`
  3975. Age uint8 `validate:"gte=0,lte=130"`
  3976. Email string `validate:"required,email"`
  3977. FavouriteColor string `validate:"hexcolor|rgb|rgba"`
  3978. Addresses []*Address `validate:"required"` // a person can have a home and cottage...
  3979. Address Address `validate:"structonly"` // a person can have a home and cottage...
  3980. }
  3981. address := &Address{
  3982. Street: "Eavesdown Docks",
  3983. Planet: "Persphone",
  3984. Phone: "none",
  3985. City: "Unknown",
  3986. }
  3987. user := &User{
  3988. FirstName: "",
  3989. LastName: "",
  3990. Age: 45,
  3991. Email: "Badger.Smith@gmail.com",
  3992. FavouriteColor: "#000",
  3993. Addresses: []*Address{address},
  3994. Address: Address{
  3995. // Street: "Eavesdown Docks",
  3996. Planet: "Persphone",
  3997. Phone: "none",
  3998. City: "Unknown",
  3999. },
  4000. }
  4001. errs = validate.Struct(user)
  4002. Equal(t, errs, nil)
  4003. }
  4004. func TestGtField(t *testing.T) {
  4005. validate := New()
  4006. type TimeTest struct {
  4007. Start *time.Time `validate:"required,gt"`
  4008. End *time.Time `validate:"required,gt,gtfield=Start"`
  4009. }
  4010. now := time.Now()
  4011. start := now.Add(time.Hour * 24)
  4012. end := start.Add(time.Hour * 24)
  4013. timeTest := &TimeTest{
  4014. Start: &start,
  4015. End: &end,
  4016. }
  4017. errs := validate.Struct(timeTest)
  4018. Equal(t, errs, nil)
  4019. timeTest = &TimeTest{
  4020. Start: &end,
  4021. End: &start,
  4022. }
  4023. errs = validate.Struct(timeTest)
  4024. NotEqual(t, errs, nil)
  4025. AssertError(t, errs, "TimeTest.End", "TimeTest.End", "End", "End", "gtfield")
  4026. errs = validate.VarWithValue(&end, &start, "gtfield")
  4027. Equal(t, errs, nil)
  4028. errs = validate.VarWithValue(&start, &end, "gtfield")
  4029. NotEqual(t, errs, nil)
  4030. AssertError(t, errs, "", "", "", "", "gtfield")
  4031. errs = validate.VarWithValue(&end, &start, "gtfield")
  4032. Equal(t, errs, nil)
  4033. errs = validate.VarWithValue(&timeTest, &end, "gtfield")
  4034. NotEqual(t, errs, nil)
  4035. errs = validate.VarWithValue("test bigger", "test", "gtfield")
  4036. Equal(t, errs, nil)
  4037. type IntTest struct {
  4038. Val1 int `validate:"required"`
  4039. Val2 int `validate:"required,gtfield=Val1"`
  4040. }
  4041. intTest := &IntTest{
  4042. Val1: 1,
  4043. Val2: 5,
  4044. }
  4045. errs = validate.Struct(intTest)
  4046. Equal(t, errs, nil)
  4047. intTest = &IntTest{
  4048. Val1: 5,
  4049. Val2: 1,
  4050. }
  4051. errs = validate.Struct(intTest)
  4052. NotEqual(t, errs, nil)
  4053. AssertError(t, errs, "IntTest.Val2", "IntTest.Val2", "Val2", "Val2", "gtfield")
  4054. errs = validate.VarWithValue(int(5), int(1), "gtfield")
  4055. Equal(t, errs, nil)
  4056. errs = validate.VarWithValue(int(1), int(5), "gtfield")
  4057. NotEqual(t, errs, nil)
  4058. AssertError(t, errs, "", "", "", "", "gtfield")
  4059. type UIntTest struct {
  4060. Val1 uint `validate:"required"`
  4061. Val2 uint `validate:"required,gtfield=Val1"`
  4062. }
  4063. uIntTest := &UIntTest{
  4064. Val1: 1,
  4065. Val2: 5,
  4066. }
  4067. errs = validate.Struct(uIntTest)
  4068. Equal(t, errs, nil)
  4069. uIntTest = &UIntTest{
  4070. Val1: 5,
  4071. Val2: 1,
  4072. }
  4073. errs = validate.Struct(uIntTest)
  4074. NotEqual(t, errs, nil)
  4075. AssertError(t, errs, "UIntTest.Val2", "UIntTest.Val2", "Val2", "Val2", "gtfield")
  4076. errs = validate.VarWithValue(uint(5), uint(1), "gtfield")
  4077. Equal(t, errs, nil)
  4078. errs = validate.VarWithValue(uint(1), uint(5), "gtfield")
  4079. NotEqual(t, errs, nil)
  4080. AssertError(t, errs, "", "", "", "", "gtfield")
  4081. type FloatTest struct {
  4082. Val1 float64 `validate:"required"`
  4083. Val2 float64 `validate:"required,gtfield=Val1"`
  4084. }
  4085. floatTest := &FloatTest{
  4086. Val1: 1,
  4087. Val2: 5,
  4088. }
  4089. errs = validate.Struct(floatTest)
  4090. Equal(t, errs, nil)
  4091. floatTest = &FloatTest{
  4092. Val1: 5,
  4093. Val2: 1,
  4094. }
  4095. errs = validate.Struct(floatTest)
  4096. NotEqual(t, errs, nil)
  4097. AssertError(t, errs, "FloatTest.Val2", "FloatTest.Val2", "Val2", "Val2", "gtfield")
  4098. errs = validate.VarWithValue(float32(5), float32(1), "gtfield")
  4099. Equal(t, errs, nil)
  4100. errs = validate.VarWithValue(float32(1), float32(5), "gtfield")
  4101. NotEqual(t, errs, nil)
  4102. AssertError(t, errs, "", "", "", "", "gtfield")
  4103. errs = validate.VarWithValue(nil, 1, "gtfield")
  4104. NotEqual(t, errs, nil)
  4105. AssertError(t, errs, "", "", "", "", "gtfield")
  4106. errs = validate.VarWithValue(5, "T", "gtfield")
  4107. NotEqual(t, errs, nil)
  4108. AssertError(t, errs, "", "", "", "", "gtfield")
  4109. errs = validate.VarWithValue(5, start, "gtfield")
  4110. NotEqual(t, errs, nil)
  4111. AssertError(t, errs, "", "", "", "", "gtfield")
  4112. type TimeTest2 struct {
  4113. Start *time.Time `validate:"required"`
  4114. End *time.Time `validate:"required,gtfield=NonExistantField"`
  4115. }
  4116. timeTest2 := &TimeTest2{
  4117. Start: &start,
  4118. End: &end,
  4119. }
  4120. errs = validate.Struct(timeTest2)
  4121. NotEqual(t, errs, nil)
  4122. AssertError(t, errs, "TimeTest2.End", "TimeTest2.End", "End", "End", "gtfield")
  4123. type Other struct {
  4124. Value string
  4125. }
  4126. type Test struct {
  4127. Value Other
  4128. Time time.Time `validate:"gtfield=Value"`
  4129. }
  4130. tst := Test{
  4131. Value: Other{Value: "StringVal"},
  4132. Time: end,
  4133. }
  4134. errs = validate.Struct(tst)
  4135. NotEqual(t, errs, nil)
  4136. AssertError(t, errs, "Test.Time", "Test.Time", "Time", "Time", "gtfield")
  4137. }
  4138. func TestLtField(t *testing.T) {
  4139. validate := New()
  4140. type TimeTest struct {
  4141. Start *time.Time `validate:"required,lt,ltfield=End"`
  4142. End *time.Time `validate:"required,lt"`
  4143. }
  4144. now := time.Now()
  4145. start := now.Add(time.Hour * 24 * -1 * 2)
  4146. end := start.Add(time.Hour * 24)
  4147. timeTest := &TimeTest{
  4148. Start: &start,
  4149. End: &end,
  4150. }
  4151. errs := validate.Struct(timeTest)
  4152. Equal(t, errs, nil)
  4153. timeTest = &TimeTest{
  4154. Start: &end,
  4155. End: &start,
  4156. }
  4157. errs = validate.Struct(timeTest)
  4158. NotEqual(t, errs, nil)
  4159. AssertError(t, errs, "TimeTest.Start", "TimeTest.Start", "Start", "Start", "ltfield")
  4160. errs = validate.VarWithValue(&start, &end, "ltfield")
  4161. Equal(t, errs, nil)
  4162. errs = validate.VarWithValue(&end, &start, "ltfield")
  4163. NotEqual(t, errs, nil)
  4164. AssertError(t, errs, "", "", "", "", "ltfield")
  4165. errs = validate.VarWithValue(&end, timeTest, "ltfield")
  4166. NotEqual(t, errs, nil)
  4167. AssertError(t, errs, "", "", "", "", "ltfield")
  4168. errs = validate.VarWithValue("tes", "test", "ltfield")
  4169. Equal(t, errs, nil)
  4170. type IntTest struct {
  4171. Val1 int `validate:"required"`
  4172. Val2 int `validate:"required,ltfield=Val1"`
  4173. }
  4174. intTest := &IntTest{
  4175. Val1: 5,
  4176. Val2: 1,
  4177. }
  4178. errs = validate.Struct(intTest)
  4179. Equal(t, errs, nil)
  4180. intTest = &IntTest{
  4181. Val1: 1,
  4182. Val2: 5,
  4183. }
  4184. errs = validate.Struct(intTest)
  4185. NotEqual(t, errs, nil)
  4186. AssertError(t, errs, "IntTest.Val2", "IntTest.Val2", "Val2", "Val2", "ltfield")
  4187. errs = validate.VarWithValue(int(1), int(5), "ltfield")
  4188. Equal(t, errs, nil)
  4189. errs = validate.VarWithValue(int(5), int(1), "ltfield")
  4190. NotEqual(t, errs, nil)
  4191. AssertError(t, errs, "", "", "", "", "ltfield")
  4192. type UIntTest struct {
  4193. Val1 uint `validate:"required"`
  4194. Val2 uint `validate:"required,ltfield=Val1"`
  4195. }
  4196. uIntTest := &UIntTest{
  4197. Val1: 5,
  4198. Val2: 1,
  4199. }
  4200. errs = validate.Struct(uIntTest)
  4201. Equal(t, errs, nil)
  4202. uIntTest = &UIntTest{
  4203. Val1: 1,
  4204. Val2: 5,
  4205. }
  4206. errs = validate.Struct(uIntTest)
  4207. NotEqual(t, errs, nil)
  4208. AssertError(t, errs, "UIntTest.Val2", "UIntTest.Val2", "Val2", "Val2", "ltfield")
  4209. errs = validate.VarWithValue(uint(1), uint(5), "ltfield")
  4210. Equal(t, errs, nil)
  4211. errs = validate.VarWithValue(uint(5), uint(1), "ltfield")
  4212. NotEqual(t, errs, nil)
  4213. AssertError(t, errs, "", "", "", "", "ltfield")
  4214. type FloatTest struct {
  4215. Val1 float64 `validate:"required"`
  4216. Val2 float64 `validate:"required,ltfield=Val1"`
  4217. }
  4218. floatTest := &FloatTest{
  4219. Val1: 5,
  4220. Val2: 1,
  4221. }
  4222. errs = validate.Struct(floatTest)
  4223. Equal(t, errs, nil)
  4224. floatTest = &FloatTest{
  4225. Val1: 1,
  4226. Val2: 5,
  4227. }
  4228. errs = validate.Struct(floatTest)
  4229. NotEqual(t, errs, nil)
  4230. AssertError(t, errs, "FloatTest.Val2", "FloatTest.Val2", "Val2", "Val2", "ltfield")
  4231. errs = validate.VarWithValue(float32(1), float32(5), "ltfield")
  4232. Equal(t, errs, nil)
  4233. errs = validate.VarWithValue(float32(5), float32(1), "ltfield")
  4234. NotEqual(t, errs, nil)
  4235. AssertError(t, errs, "", "", "", "", "ltfield")
  4236. errs = validate.VarWithValue(nil, 5, "ltfield")
  4237. NotEqual(t, errs, nil)
  4238. AssertError(t, errs, "", "", "", "", "ltfield")
  4239. errs = validate.VarWithValue(1, "T", "ltfield")
  4240. NotEqual(t, errs, nil)
  4241. AssertError(t, errs, "", "", "", "", "ltfield")
  4242. errs = validate.VarWithValue(1, end, "ltfield")
  4243. NotEqual(t, errs, nil)
  4244. AssertError(t, errs, "", "", "", "", "ltfield")
  4245. type TimeTest2 struct {
  4246. Start *time.Time `validate:"required"`
  4247. End *time.Time `validate:"required,ltfield=NonExistantField"`
  4248. }
  4249. timeTest2 := &TimeTest2{
  4250. Start: &end,
  4251. End: &start,
  4252. }
  4253. errs = validate.Struct(timeTest2)
  4254. NotEqual(t, errs, nil)
  4255. AssertError(t, errs, "TimeTest2.End", "TimeTest2.End", "End", "End", "ltfield")
  4256. }
  4257. func TestFieldContains(t *testing.T) {
  4258. validate := New()
  4259. type StringTest struct {
  4260. Foo string `validate:"fieldcontains=Bar"`
  4261. Bar string
  4262. }
  4263. stringTest := &StringTest{
  4264. Foo: "foobar",
  4265. Bar: "bar",
  4266. }
  4267. errs := validate.Struct(stringTest)
  4268. Equal(t, errs, nil)
  4269. stringTest = &StringTest{
  4270. Foo: "foo",
  4271. Bar: "bar",
  4272. }
  4273. errs = validate.Struct(stringTest)
  4274. NotEqual(t, errs, nil)
  4275. AssertError(t, errs, "StringTest.Foo", "StringTest.Foo", "Foo", "Foo", "fieldcontains")
  4276. errs = validate.VarWithValue("foo", "bar", "fieldcontains")
  4277. NotEqual(t, errs, nil)
  4278. AssertError(t, errs, "", "", "", "", "fieldcontains")
  4279. errs = validate.VarWithValue("bar", "foobarfoo", "fieldcontains")
  4280. NotEqual(t, errs, nil)
  4281. AssertError(t, errs, "", "", "", "", "fieldcontains")
  4282. errs = validate.VarWithValue("foobarfoo", "bar", "fieldcontains")
  4283. Equal(t, errs, nil)
  4284. type StringTestMissingField struct {
  4285. Foo string `validate:"fieldcontains=Bar"`
  4286. }
  4287. stringTestMissingField := &StringTestMissingField{
  4288. Foo: "foo",
  4289. }
  4290. errs = validate.Struct(stringTestMissingField)
  4291. NotEqual(t, errs, nil)
  4292. AssertError(t, errs, "StringTestMissingField.Foo", "StringTestMissingField.Foo", "Foo", "Foo", "fieldcontains")
  4293. }
  4294. func TestFieldExcludes(t *testing.T) {
  4295. validate := New()
  4296. type StringTest struct {
  4297. Foo string `validate:"fieldexcludes=Bar"`
  4298. Bar string
  4299. }
  4300. stringTest := &StringTest{
  4301. Foo: "foobar",
  4302. Bar: "bar",
  4303. }
  4304. errs := validate.Struct(stringTest)
  4305. NotEqual(t, errs, nil)
  4306. AssertError(t, errs, "StringTest.Foo", "StringTest.Foo", "Foo", "Foo", "fieldexcludes")
  4307. stringTest = &StringTest{
  4308. Foo: "foo",
  4309. Bar: "bar",
  4310. }
  4311. errs = validate.Struct(stringTest)
  4312. Equal(t, errs, nil)
  4313. errs = validate.VarWithValue("foo", "bar", "fieldexcludes")
  4314. Equal(t, errs, nil)
  4315. errs = validate.VarWithValue("bar", "foobarfoo", "fieldexcludes")
  4316. Equal(t, errs, nil)
  4317. errs = validate.VarWithValue("foobarfoo", "bar", "fieldexcludes")
  4318. NotEqual(t, errs, nil)
  4319. AssertError(t, errs, "", "", "", "", "fieldexcludes")
  4320. type StringTestMissingField struct {
  4321. Foo string `validate:"fieldexcludes=Bar"`
  4322. }
  4323. stringTestMissingField := &StringTestMissingField{
  4324. Foo: "foo",
  4325. }
  4326. errs = validate.Struct(stringTestMissingField)
  4327. Equal(t, errs, nil)
  4328. }
  4329. func TestContainsAndExcludes(t *testing.T) {
  4330. validate := New()
  4331. type ImpossibleStringTest struct {
  4332. Foo string `validate:"fieldcontains=Bar"`
  4333. Bar string `validate:"fieldexcludes=Foo"`
  4334. }
  4335. impossibleStringTest := &ImpossibleStringTest{
  4336. Foo: "foo",
  4337. Bar: "bar",
  4338. }
  4339. errs := validate.Struct(impossibleStringTest)
  4340. NotEqual(t, errs, nil)
  4341. AssertError(t, errs, "ImpossibleStringTest.Foo", "ImpossibleStringTest.Foo", "Foo", "Foo", "fieldcontains")
  4342. impossibleStringTest = &ImpossibleStringTest{
  4343. Foo: "bar",
  4344. Bar: "foo",
  4345. }
  4346. errs = validate.Struct(impossibleStringTest)
  4347. NotEqual(t, errs, nil)
  4348. AssertError(t, errs, "ImpossibleStringTest.Foo", "ImpossibleStringTest.Foo", "Foo", "Foo", "fieldcontains")
  4349. }
  4350. func TestLteField(t *testing.T) {
  4351. validate := New()
  4352. type TimeTest struct {
  4353. Start *time.Time `validate:"required,lte,ltefield=End"`
  4354. End *time.Time `validate:"required,lte"`
  4355. }
  4356. now := time.Now()
  4357. start := now.Add(time.Hour * 24 * -1 * 2)
  4358. end := start.Add(time.Hour * 24)
  4359. timeTest := &TimeTest{
  4360. Start: &start,
  4361. End: &end,
  4362. }
  4363. errs := validate.Struct(timeTest)
  4364. Equal(t, errs, nil)
  4365. timeTest = &TimeTest{
  4366. Start: &end,
  4367. End: &start,
  4368. }
  4369. errs = validate.Struct(timeTest)
  4370. NotEqual(t, errs, nil)
  4371. AssertError(t, errs, "TimeTest.Start", "TimeTest.Start", "Start", "Start", "ltefield")
  4372. errs = validate.VarWithValue(&start, &end, "ltefield")
  4373. Equal(t, errs, nil)
  4374. errs = validate.VarWithValue(&end, &start, "ltefield")
  4375. NotEqual(t, errs, nil)
  4376. AssertError(t, errs, "", "", "", "", "ltefield")
  4377. errs = validate.VarWithValue(&end, timeTest, "ltefield")
  4378. NotEqual(t, errs, nil)
  4379. AssertError(t, errs, "", "", "", "", "ltefield")
  4380. errs = validate.VarWithValue("tes", "test", "ltefield")
  4381. Equal(t, errs, nil)
  4382. errs = validate.VarWithValue("test", "test", "ltefield")
  4383. Equal(t, errs, nil)
  4384. type IntTest struct {
  4385. Val1 int `validate:"required"`
  4386. Val2 int `validate:"required,ltefield=Val1"`
  4387. }
  4388. intTest := &IntTest{
  4389. Val1: 5,
  4390. Val2: 1,
  4391. }
  4392. errs = validate.Struct(intTest)
  4393. Equal(t, errs, nil)
  4394. intTest = &IntTest{
  4395. Val1: 1,
  4396. Val2: 5,
  4397. }
  4398. errs = validate.Struct(intTest)
  4399. NotEqual(t, errs, nil)
  4400. AssertError(t, errs, "IntTest.Val2", "IntTest.Val2", "Val2", "Val2", "ltefield")
  4401. errs = validate.VarWithValue(int(1), int(5), "ltefield")
  4402. Equal(t, errs, nil)
  4403. errs = validate.VarWithValue(int(5), int(1), "ltefield")
  4404. NotEqual(t, errs, nil)
  4405. AssertError(t, errs, "", "", "", "", "ltefield")
  4406. type UIntTest struct {
  4407. Val1 uint `validate:"required"`
  4408. Val2 uint `validate:"required,ltefield=Val1"`
  4409. }
  4410. uIntTest := &UIntTest{
  4411. Val1: 5,
  4412. Val2: 1,
  4413. }
  4414. errs = validate.Struct(uIntTest)
  4415. Equal(t, errs, nil)
  4416. uIntTest = &UIntTest{
  4417. Val1: 1,
  4418. Val2: 5,
  4419. }
  4420. errs = validate.Struct(uIntTest)
  4421. NotEqual(t, errs, nil)
  4422. AssertError(t, errs, "UIntTest.Val2", "UIntTest.Val2", "Val2", "Val2", "ltefield")
  4423. errs = validate.VarWithValue(uint(1), uint(5), "ltefield")
  4424. Equal(t, errs, nil)
  4425. errs = validate.VarWithValue(uint(5), uint(1), "ltefield")
  4426. NotEqual(t, errs, nil)
  4427. AssertError(t, errs, "", "", "", "", "ltefield")
  4428. type FloatTest struct {
  4429. Val1 float64 `validate:"required"`
  4430. Val2 float64 `validate:"required,ltefield=Val1"`
  4431. }
  4432. floatTest := &FloatTest{
  4433. Val1: 5,
  4434. Val2: 1,
  4435. }
  4436. errs = validate.Struct(floatTest)
  4437. Equal(t, errs, nil)
  4438. floatTest = &FloatTest{
  4439. Val1: 1,
  4440. Val2: 5,
  4441. }
  4442. errs = validate.Struct(floatTest)
  4443. NotEqual(t, errs, nil)
  4444. AssertError(t, errs, "FloatTest.Val2", "FloatTest.Val2", "Val2", "Val2", "ltefield")
  4445. errs = validate.VarWithValue(float32(1), float32(5), "ltefield")
  4446. Equal(t, errs, nil)
  4447. errs = validate.VarWithValue(float32(5), float32(1), "ltefield")
  4448. NotEqual(t, errs, nil)
  4449. AssertError(t, errs, "", "", "", "", "ltefield")
  4450. errs = validate.VarWithValue(nil, 5, "ltefield")
  4451. NotEqual(t, errs, nil)
  4452. AssertError(t, errs, "", "", "", "", "ltefield")
  4453. errs = validate.VarWithValue(1, "T", "ltefield")
  4454. NotEqual(t, errs, nil)
  4455. AssertError(t, errs, "", "", "", "", "ltefield")
  4456. errs = validate.VarWithValue(1, end, "ltefield")
  4457. NotEqual(t, errs, nil)
  4458. AssertError(t, errs, "", "", "", "", "ltefield")
  4459. type TimeTest2 struct {
  4460. Start *time.Time `validate:"required"`
  4461. End *time.Time `validate:"required,ltefield=NonExistantField"`
  4462. }
  4463. timeTest2 := &TimeTest2{
  4464. Start: &end,
  4465. End: &start,
  4466. }
  4467. errs = validate.Struct(timeTest2)
  4468. NotEqual(t, errs, nil)
  4469. AssertError(t, errs, "TimeTest2.End", "TimeTest2.End", "End", "End", "ltefield")
  4470. }
  4471. func TestGteField(t *testing.T) {
  4472. validate := New()
  4473. type TimeTest struct {
  4474. Start *time.Time `validate:"required,gte"`
  4475. End *time.Time `validate:"required,gte,gtefield=Start"`
  4476. }
  4477. now := time.Now()
  4478. start := now.Add(time.Hour * 24)
  4479. end := start.Add(time.Hour * 24)
  4480. timeTest := &TimeTest{
  4481. Start: &start,
  4482. End: &end,
  4483. }
  4484. errs := validate.Struct(timeTest)
  4485. Equal(t, errs, nil)
  4486. timeTest = &TimeTest{
  4487. Start: &end,
  4488. End: &start,
  4489. }
  4490. errs = validate.Struct(timeTest)
  4491. NotEqual(t, errs, nil)
  4492. AssertError(t, errs, "TimeTest.End", "TimeTest.End", "End", "End", "gtefield")
  4493. errs = validate.VarWithValue(&end, &start, "gtefield")
  4494. Equal(t, errs, nil)
  4495. errs = validate.VarWithValue(&start, &end, "gtefield")
  4496. NotEqual(t, errs, nil)
  4497. AssertError(t, errs, "", "", "", "", "gtefield")
  4498. errs = validate.VarWithValue(&start, timeTest, "gtefield")
  4499. NotEqual(t, errs, nil)
  4500. AssertError(t, errs, "", "", "", "", "gtefield")
  4501. errs = validate.VarWithValue("test", "test", "gtefield")
  4502. Equal(t, errs, nil)
  4503. errs = validate.VarWithValue("test bigger", "test", "gtefield")
  4504. Equal(t, errs, nil)
  4505. type IntTest struct {
  4506. Val1 int `validate:"required"`
  4507. Val2 int `validate:"required,gtefield=Val1"`
  4508. }
  4509. intTest := &IntTest{
  4510. Val1: 1,
  4511. Val2: 5,
  4512. }
  4513. errs = validate.Struct(intTest)
  4514. Equal(t, errs, nil)
  4515. intTest = &IntTest{
  4516. Val1: 5,
  4517. Val2: 1,
  4518. }
  4519. errs = validate.Struct(intTest)
  4520. NotEqual(t, errs, nil)
  4521. AssertError(t, errs, "IntTest.Val2", "IntTest.Val2", "Val2", "Val2", "gtefield")
  4522. errs = validate.VarWithValue(int(5), int(1), "gtefield")
  4523. Equal(t, errs, nil)
  4524. errs = validate.VarWithValue(int(1), int(5), "gtefield")
  4525. NotEqual(t, errs, nil)
  4526. AssertError(t, errs, "", "", "", "", "gtefield")
  4527. type UIntTest struct {
  4528. Val1 uint `validate:"required"`
  4529. Val2 uint `validate:"required,gtefield=Val1"`
  4530. }
  4531. uIntTest := &UIntTest{
  4532. Val1: 1,
  4533. Val2: 5,
  4534. }
  4535. errs = validate.Struct(uIntTest)
  4536. Equal(t, errs, nil)
  4537. uIntTest = &UIntTest{
  4538. Val1: 5,
  4539. Val2: 1,
  4540. }
  4541. errs = validate.Struct(uIntTest)
  4542. NotEqual(t, errs, nil)
  4543. AssertError(t, errs, "UIntTest.Val2", "UIntTest.Val2", "Val2", "Val2", "gtefield")
  4544. errs = validate.VarWithValue(uint(5), uint(1), "gtefield")
  4545. Equal(t, errs, nil)
  4546. errs = validate.VarWithValue(uint(1), uint(5), "gtefield")
  4547. NotEqual(t, errs, nil)
  4548. AssertError(t, errs, "", "", "", "", "gtefield")
  4549. type FloatTest struct {
  4550. Val1 float64 `validate:"required"`
  4551. Val2 float64 `validate:"required,gtefield=Val1"`
  4552. }
  4553. floatTest := &FloatTest{
  4554. Val1: 1,
  4555. Val2: 5,
  4556. }
  4557. errs = validate.Struct(floatTest)
  4558. Equal(t, errs, nil)
  4559. floatTest = &FloatTest{
  4560. Val1: 5,
  4561. Val2: 1,
  4562. }
  4563. errs = validate.Struct(floatTest)
  4564. NotEqual(t, errs, nil)
  4565. AssertError(t, errs, "FloatTest.Val2", "FloatTest.Val2", "Val2", "Val2", "gtefield")
  4566. errs = validate.VarWithValue(float32(5), float32(1), "gtefield")
  4567. Equal(t, errs, nil)
  4568. errs = validate.VarWithValue(float32(1), float32(5), "gtefield")
  4569. NotEqual(t, errs, nil)
  4570. AssertError(t, errs, "", "", "", "", "gtefield")
  4571. errs = validate.VarWithValue(nil, 1, "gtefield")
  4572. NotEqual(t, errs, nil)
  4573. AssertError(t, errs, "", "", "", "", "gtefield")
  4574. errs = validate.VarWithValue(5, "T", "gtefield")
  4575. NotEqual(t, errs, nil)
  4576. AssertError(t, errs, "", "", "", "", "gtefield")
  4577. errs = validate.VarWithValue(5, start, "gtefield")
  4578. NotEqual(t, errs, nil)
  4579. AssertError(t, errs, "", "", "", "", "gtefield")
  4580. type TimeTest2 struct {
  4581. Start *time.Time `validate:"required"`
  4582. End *time.Time `validate:"required,gtefield=NonExistantField"`
  4583. }
  4584. timeTest2 := &TimeTest2{
  4585. Start: &start,
  4586. End: &end,
  4587. }
  4588. errs = validate.Struct(timeTest2)
  4589. NotEqual(t, errs, nil)
  4590. AssertError(t, errs, "TimeTest2.End", "TimeTest2.End", "End", "End", "gtefield")
  4591. }
  4592. func TestValidateByTagAndValue(t *testing.T) {
  4593. validate := New()
  4594. val := "test"
  4595. field := "test"
  4596. errs := validate.VarWithValue(val, field, "required")
  4597. Equal(t, errs, nil)
  4598. fn := func(fl FieldLevel) bool {
  4599. return fl.Parent().String() == fl.Field().String()
  4600. }
  4601. validate.RegisterValidation("isequaltestfunc", fn)
  4602. errs = validate.VarWithValue(val, field, "isequaltestfunc")
  4603. Equal(t, errs, nil)
  4604. val = "unequal"
  4605. errs = validate.VarWithValue(val, field, "isequaltestfunc")
  4606. NotEqual(t, errs, nil)
  4607. AssertError(t, errs, "", "", "", "", "isequaltestfunc")
  4608. }
  4609. func TestAddFunctions(t *testing.T) {
  4610. fn := func(fl FieldLevel) bool {
  4611. return true
  4612. }
  4613. fnCtx := func(ctx context.Context, fl FieldLevel) bool {
  4614. return true
  4615. }
  4616. validate := New()
  4617. errs := validate.RegisterValidation("new", fn)
  4618. Equal(t, errs, nil)
  4619. errs = validate.RegisterValidation("", fn)
  4620. NotEqual(t, errs, nil)
  4621. validate.RegisterValidation("new", nil)
  4622. NotEqual(t, errs, nil)
  4623. errs = validate.RegisterValidation("new", fn)
  4624. Equal(t, errs, nil)
  4625. errs = validate.RegisterValidationCtx("new", fnCtx)
  4626. Equal(t, errs, nil)
  4627. PanicMatches(t, func() { validate.RegisterValidation("dive", fn) }, "Tag 'dive' either contains restricted characters or is the same as a restricted tag needed for normal operation")
  4628. }
  4629. func TestChangeTag(t *testing.T) {
  4630. validate := New()
  4631. validate.SetTagName("val")
  4632. type Test struct {
  4633. Name string `val:"len=4"`
  4634. }
  4635. s := &Test{
  4636. Name: "TEST",
  4637. }
  4638. errs := validate.Struct(s)
  4639. Equal(t, errs, nil)
  4640. s.Name = ""
  4641. errs = validate.Struct(s)
  4642. NotEqual(t, errs, nil)
  4643. AssertError(t, errs, "Test.Name", "Test.Name", "Name", "Name", "len")
  4644. }
  4645. func TestUnexposedStruct(t *testing.T) {
  4646. validate := New()
  4647. type Test struct {
  4648. Name string
  4649. unexposed struct {
  4650. A string `validate:"required"`
  4651. }
  4652. }
  4653. s := &Test{
  4654. Name: "TEST",
  4655. }
  4656. errs := validate.Struct(s)
  4657. Equal(t, errs, nil)
  4658. }
  4659. func TestBadParams(t *testing.T) {
  4660. validate := New()
  4661. i := 1
  4662. errs := validate.Var(i, "-")
  4663. Equal(t, errs, nil)
  4664. PanicMatches(t, func() { validate.Var(i, "len=a") }, "strconv.ParseInt: parsing \"a\": invalid syntax")
  4665. PanicMatches(t, func() { validate.Var(i, "len=a") }, "strconv.ParseInt: parsing \"a\": invalid syntax")
  4666. var ui uint = 1
  4667. PanicMatches(t, func() { validate.Var(ui, "len=a") }, "strconv.ParseUint: parsing \"a\": invalid syntax")
  4668. f := 1.23
  4669. PanicMatches(t, func() { validate.Var(f, "len=a") }, "strconv.ParseFloat: parsing \"a\": invalid syntax")
  4670. }
  4671. func TestLength(t *testing.T) {
  4672. validate := New()
  4673. i := true
  4674. PanicMatches(t, func() { validate.Var(i, "len") }, "Bad field type bool")
  4675. }
  4676. func TestIsGt(t *testing.T) {
  4677. validate := New()
  4678. myMap := map[string]string{}
  4679. errs := validate.Var(myMap, "gt=0")
  4680. NotEqual(t, errs, nil)
  4681. f := 1.23
  4682. errs = validate.Var(f, "gt=5")
  4683. NotEqual(t, errs, nil)
  4684. AssertError(t, errs, "", "", "", "", "gt")
  4685. var ui uint = 5
  4686. errs = validate.Var(ui, "gt=10")
  4687. NotEqual(t, errs, nil)
  4688. AssertError(t, errs, "", "", "", "", "gt")
  4689. i := true
  4690. PanicMatches(t, func() { validate.Var(i, "gt") }, "Bad field type bool")
  4691. tm := time.Now().UTC()
  4692. tm = tm.Add(time.Hour * 24)
  4693. errs = validate.Var(tm, "gt")
  4694. Equal(t, errs, nil)
  4695. t2 := time.Now().UTC().Add(-time.Hour)
  4696. errs = validate.Var(t2, "gt")
  4697. NotEqual(t, errs, nil)
  4698. AssertError(t, errs, "", "", "", "", "gt")
  4699. type Test struct {
  4700. Now *time.Time `validate:"gt"`
  4701. }
  4702. s := &Test{
  4703. Now: &tm,
  4704. }
  4705. errs = validate.Struct(s)
  4706. Equal(t, errs, nil)
  4707. s = &Test{
  4708. Now: &t2,
  4709. }
  4710. errs = validate.Struct(s)
  4711. NotEqual(t, errs, nil)
  4712. AssertError(t, errs, "Test.Now", "Test.Now", "Now", "Now", "gt")
  4713. }
  4714. func TestIsGte(t *testing.T) {
  4715. validate := New()
  4716. i := true
  4717. PanicMatches(t, func() { validate.Var(i, "gte") }, "Bad field type bool")
  4718. t1 := time.Now().UTC()
  4719. t1 = t1.Add(time.Hour * 24)
  4720. errs := validate.Var(t1, "gte")
  4721. Equal(t, errs, nil)
  4722. t2 := time.Now().UTC().Add(-time.Hour)
  4723. errs = validate.Var(t2, "gte")
  4724. NotEqual(t, errs, nil)
  4725. AssertError(t, errs, "", "", "", "", "gte")
  4726. type Test struct {
  4727. Now *time.Time `validate:"gte"`
  4728. }
  4729. s := &Test{
  4730. Now: &t1,
  4731. }
  4732. errs = validate.Struct(s)
  4733. Equal(t, errs, nil)
  4734. s = &Test{
  4735. Now: &t2,
  4736. }
  4737. errs = validate.Struct(s)
  4738. NotEqual(t, errs, nil)
  4739. AssertError(t, errs, "Test.Now", "Test.Now", "Now", "Now", "gte")
  4740. }
  4741. func TestIsLt(t *testing.T) {
  4742. validate := New()
  4743. myMap := map[string]string{}
  4744. errs := validate.Var(myMap, "lt=0")
  4745. NotEqual(t, errs, nil)
  4746. AssertError(t, errs, "", "", "", "", "lt")
  4747. f := 1.23
  4748. errs = validate.Var(f, "lt=0")
  4749. NotEqual(t, errs, nil)
  4750. AssertError(t, errs, "", "", "", "", "lt")
  4751. var ui uint = 5
  4752. errs = validate.Var(ui, "lt=0")
  4753. NotEqual(t, errs, nil)
  4754. AssertError(t, errs, "", "", "", "", "lt")
  4755. i := true
  4756. PanicMatches(t, func() { validate.Var(i, "lt") }, "Bad field type bool")
  4757. t1 := time.Now().UTC().Add(-time.Hour)
  4758. errs = validate.Var(t1, "lt")
  4759. Equal(t, errs, nil)
  4760. t2 := time.Now().UTC()
  4761. t2 = t2.Add(time.Hour * 24)
  4762. errs = validate.Var(t2, "lt")
  4763. NotEqual(t, errs, nil)
  4764. AssertError(t, errs, "", "", "", "", "lt")
  4765. type Test struct {
  4766. Now *time.Time `validate:"lt"`
  4767. }
  4768. s := &Test{
  4769. Now: &t1,
  4770. }
  4771. errs = validate.Struct(s)
  4772. Equal(t, errs, nil)
  4773. s = &Test{
  4774. Now: &t2,
  4775. }
  4776. errs = validate.Struct(s)
  4777. NotEqual(t, errs, nil)
  4778. AssertError(t, errs, "Test.Now", "Test.Now", "Now", "Now", "lt")
  4779. }
  4780. func TestIsLte(t *testing.T) {
  4781. validate := New()
  4782. i := true
  4783. PanicMatches(t, func() { validate.Var(i, "lte") }, "Bad field type bool")
  4784. t1 := time.Now().UTC().Add(-time.Hour)
  4785. errs := validate.Var(t1, "lte")
  4786. Equal(t, errs, nil)
  4787. t2 := time.Now().UTC()
  4788. t2 = t2.Add(time.Hour * 24)
  4789. errs = validate.Var(t2, "lte")
  4790. NotEqual(t, errs, nil)
  4791. AssertError(t, errs, "", "", "", "", "lte")
  4792. type Test struct {
  4793. Now *time.Time `validate:"lte"`
  4794. }
  4795. s := &Test{
  4796. Now: &t1,
  4797. }
  4798. errs = validate.Struct(s)
  4799. Equal(t, errs, nil)
  4800. s = &Test{
  4801. Now: &t2,
  4802. }
  4803. errs = validate.Struct(s)
  4804. NotEqual(t, errs, nil)
  4805. }
  4806. func TestUrnRFC2141(t *testing.T) {
  4807. var tests = []struct {
  4808. param string
  4809. expected bool
  4810. }{
  4811. {"urn:a:b", true},
  4812. {"urn:a::", true},
  4813. {"urn:a:-", true},
  4814. {"URN:simple:simple", true},
  4815. {"urn:urna:simple", true},
  4816. {"urn:burnout:nss", true},
  4817. {"urn:burn:nss", true},
  4818. {"urn:urnurnurn:x", true},
  4819. {"urn:abcdefghilmnopqrstuvzabcdefghilm:x", true},
  4820. {"URN:123:x", true},
  4821. {"URN:abcd-:x", true},
  4822. {"URN:abcd-abcd:x", true},
  4823. {"urn:urnx:urn", true},
  4824. {"urn:ciao:a:b:c", true},
  4825. {"urn:aaa:x:y:", true},
  4826. {"urn:ciao:-", true},
  4827. {"urn:colon:::::nss", true},
  4828. {"urn:ciao:@!=%2C(xyz)+a,b.*@g=$_'", true},
  4829. {"URN:hexes:%25", true},
  4830. {"URN:x:abc%1Dz%2F%3az", true},
  4831. {"URN:foo:a123,456", true},
  4832. {"urn:foo:a123,456", true},
  4833. {"urn:FOO:a123,456", true},
  4834. {"urn:foo:A123,456", true},
  4835. {"urn:foo:a123%2C456", true},
  4836. {"URN:FOO:a123%2c456", true},
  4837. {"URN:FOO:ABC%FFabc123%2c456", true},
  4838. {"URN:FOO:ABC%FFabc123%2C456%9A", true},
  4839. {"urn:ietf:params:scim:schemas:core:2.0:User", true},
  4840. {"urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:meta.lastModified", true},
  4841. {"URN:-xxx:x", false},
  4842. {"urn::colon:nss", false},
  4843. {"urn:abcdefghilmnopqrstuvzabcdefghilmn:specificstring", false},
  4844. {"URN:a!?:x", false},
  4845. {"URN:#,:x", false},
  4846. {"urn:urn:NSS", false},
  4847. {"urn:URN:NSS", false},
  4848. {"urn:white space:NSS", false},
  4849. {"urn:concat:no spaces", false},
  4850. {"urn:a:%", false},
  4851. {"urn:", false},
  4852. }
  4853. tag := "urn_rfc2141"
  4854. validate := New()
  4855. for i, test := range tests {
  4856. errs := validate.Var(test.param, tag)
  4857. if test.expected {
  4858. if !IsEqual(errs, nil) {
  4859. t.Fatalf("Index: %d URN failed Error: %s", i, errs)
  4860. }
  4861. } else {
  4862. if IsEqual(errs, nil) {
  4863. t.Fatalf("Index: %d URN failed Error: %s", i, errs)
  4864. } else {
  4865. val := getError(errs, "", "")
  4866. if val.Tag() != tag {
  4867. t.Fatalf("Index: %d URN failed Error: %s", i, errs)
  4868. }
  4869. }
  4870. }
  4871. }
  4872. i := 1
  4873. PanicMatches(t, func() { validate.Var(i, tag) }, "Bad field type int")
  4874. }
  4875. func TestUrl(t *testing.T) {
  4876. var tests = []struct {
  4877. param string
  4878. expected bool
  4879. }{
  4880. {"http://foo.bar#com", true},
  4881. {"http://foobar.com", true},
  4882. {"https://foobar.com", true},
  4883. {"foobar.com", false},
  4884. {"http://foobar.coffee/", true},
  4885. {"http://foobar.中文网/", true},
  4886. {"http://foobar.org/", true},
  4887. {"http://foobar.org:8080/", true},
  4888. {"ftp://foobar.ru/", true},
  4889. {"http://user:pass@www.foobar.com/", true},
  4890. {"http://127.0.0.1/", true},
  4891. {"http://duckduckgo.com/?q=%2F", true},
  4892. {"http://localhost:3000/", true},
  4893. {"http://foobar.com/?foo=bar#baz=qux", true},
  4894. {"http://foobar.com?foo=bar", true},
  4895. {"http://www.xn--froschgrn-x9a.net/", true},
  4896. {"", false},
  4897. {"xyz://foobar.com", true},
  4898. {"invalid.", false},
  4899. {".com", false},
  4900. {"rtmp://foobar.com", true},
  4901. {"http://www.foo_bar.com/", true},
  4902. {"http://localhost:3000/", true},
  4903. {"http://foobar.com/#baz", true},
  4904. {"http://foobar.com#baz=qux", true},
  4905. {"http://foobar.com/t$-_.+!*\\'(),", true},
  4906. {"http://www.foobar.com/~foobar", true},
  4907. {"http://www.-foobar.com/", true},
  4908. {"http://www.foo---bar.com/", true},
  4909. {"mailto:someone@example.com", true},
  4910. {"irc://irc.server.org/channel", true},
  4911. {"irc://#channel@network", true},
  4912. {"/abs/test/dir", false},
  4913. {"./rel/test/dir", false},
  4914. }
  4915. validate := New()
  4916. for i, test := range tests {
  4917. errs := validate.Var(test.param, "url")
  4918. if test.expected {
  4919. if !IsEqual(errs, nil) {
  4920. t.Fatalf("Index: %d URL failed Error: %s", i, errs)
  4921. }
  4922. } else {
  4923. if IsEqual(errs, nil) {
  4924. t.Fatalf("Index: %d URL failed Error: %s", i, errs)
  4925. } else {
  4926. val := getError(errs, "", "")
  4927. if val.Tag() != "url" {
  4928. t.Fatalf("Index: %d URL failed Error: %s", i, errs)
  4929. }
  4930. }
  4931. }
  4932. }
  4933. i := 1
  4934. PanicMatches(t, func() { validate.Var(i, "url") }, "Bad field type int")
  4935. }
  4936. func TestUri(t *testing.T) {
  4937. var tests = []struct {
  4938. param string
  4939. expected bool
  4940. }{
  4941. {"http://foo.bar#com", true},
  4942. {"http://foobar.com", true},
  4943. {"https://foobar.com", true},
  4944. {"foobar.com", false},
  4945. {"http://foobar.coffee/", true},
  4946. {"http://foobar.中文网/", true},
  4947. {"http://foobar.org/", true},
  4948. {"http://foobar.org:8080/", true},
  4949. {"ftp://foobar.ru/", true},
  4950. {"http://user:pass@www.foobar.com/", true},
  4951. {"http://127.0.0.1/", true},
  4952. {"http://duckduckgo.com/?q=%2F", true},
  4953. {"http://localhost:3000/", true},
  4954. {"http://foobar.com/?foo=bar#baz=qux", true},
  4955. {"http://foobar.com?foo=bar", true},
  4956. {"http://www.xn--froschgrn-x9a.net/", true},
  4957. {"", false},
  4958. {"xyz://foobar.com", true},
  4959. {"invalid.", false},
  4960. {".com", false},
  4961. {"rtmp://foobar.com", true},
  4962. {"http://www.foo_bar.com/", true},
  4963. {"http://localhost:3000/", true},
  4964. {"http://foobar.com#baz=qux", true},
  4965. {"http://foobar.com/t$-_.+!*\\'(),", true},
  4966. {"http://www.foobar.com/~foobar", true},
  4967. {"http://www.-foobar.com/", true},
  4968. {"http://www.foo---bar.com/", true},
  4969. {"mailto:someone@example.com", true},
  4970. {"irc://irc.server.org/channel", true},
  4971. {"irc://#channel@network", true},
  4972. {"/abs/test/dir", true},
  4973. {"./rel/test/dir", false},
  4974. }
  4975. validate := New()
  4976. for i, test := range tests {
  4977. errs := validate.Var(test.param, "uri")
  4978. if test.expected {
  4979. if !IsEqual(errs, nil) {
  4980. t.Fatalf("Index: %d URI failed Error: %s", i, errs)
  4981. }
  4982. } else {
  4983. if IsEqual(errs, nil) {
  4984. t.Fatalf("Index: %d URI failed Error: %s", i, errs)
  4985. } else {
  4986. val := getError(errs, "", "")
  4987. if val.Tag() != "uri" {
  4988. t.Fatalf("Index: %d URI failed Error: %s", i, errs)
  4989. }
  4990. }
  4991. }
  4992. }
  4993. i := 1
  4994. PanicMatches(t, func() { validate.Var(i, "uri") }, "Bad field type int")
  4995. }
  4996. func TestOrTag(t *testing.T) {
  4997. validate := New()
  4998. s := "rgba(0,31,255,0.5)"
  4999. errs := validate.Var(s, "rgb|rgba")
  5000. Equal(t, errs, nil)
  5001. s = "rgba(0,31,255,0.5)"
  5002. errs = validate.Var(s, "rgb|rgba|len=18")
  5003. Equal(t, errs, nil)
  5004. s = "this ain't right"
  5005. errs = validate.Var(s, "rgb|rgba")
  5006. NotEqual(t, errs, nil)
  5007. AssertError(t, errs, "", "", "", "", "rgb|rgba")
  5008. s = "this ain't right"
  5009. errs = validate.Var(s, "rgb|rgba|len=10")
  5010. NotEqual(t, errs, nil)
  5011. AssertError(t, errs, "", "", "", "", "rgb|rgba|len=10")
  5012. s = "this is right"
  5013. errs = validate.Var(s, "rgb|rgba|len=13")
  5014. Equal(t, errs, nil)
  5015. s = ""
  5016. errs = validate.Var(s, "omitempty,rgb|rgba")
  5017. Equal(t, errs, nil)
  5018. s = "green"
  5019. errs = validate.Var(s, "eq=|eq=blue,rgb|rgba") //should fail on first validation block
  5020. NotEqual(t, errs, nil)
  5021. ve := errs.(ValidationErrors)
  5022. Equal(t, len(ve), 1)
  5023. Equal(t, ve[0].Tag(), "eq=|eq=blue")
  5024. s = "this is right, but a blank or isn't"
  5025. PanicMatches(t, func() { validate.Var(s, "rgb||len=13") }, "Invalid validation tag on field ''")
  5026. PanicMatches(t, func() { validate.Var(s, "rgb|rgbaa|len=13") }, "Undefined validation function 'rgbaa' on field ''")
  5027. v2 := New()
  5028. v2.RegisterTagNameFunc(func(fld reflect.StructField) string {
  5029. name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
  5030. if name == "-" {
  5031. return ""
  5032. }
  5033. return name
  5034. })
  5035. type Colors struct {
  5036. Fav string `validate:"rgb|rgba" json:"fc"`
  5037. }
  5038. c := Colors{Fav: "this ain't right"}
  5039. err := v2.Struct(c)
  5040. NotEqual(t, err, nil)
  5041. errs = err.(ValidationErrors)
  5042. fe := getError(errs, "Colors.fc", "Colors.Fav")
  5043. NotEqual(t, fe, nil)
  5044. }
  5045. func TestHsla(t *testing.T) {
  5046. validate := New()
  5047. s := "hsla(360,100%,100%,1)"
  5048. errs := validate.Var(s, "hsla")
  5049. Equal(t, errs, nil)
  5050. s = "hsla(360,100%,100%,0.5)"
  5051. errs = validate.Var(s, "hsla")
  5052. Equal(t, errs, nil)
  5053. s = "hsla(0,0%,0%, 0)"
  5054. errs = validate.Var(s, "hsla")
  5055. Equal(t, errs, nil)
  5056. s = "hsl(361,100%,50%,1)"
  5057. errs = validate.Var(s, "hsla")
  5058. NotEqual(t, errs, nil)
  5059. AssertError(t, errs, "", "", "", "", "hsla")
  5060. s = "hsl(361,100%,50%)"
  5061. errs = validate.Var(s, "hsla")
  5062. NotEqual(t, errs, nil)
  5063. AssertError(t, errs, "", "", "", "", "hsla")
  5064. s = "hsla(361,100%,50%)"
  5065. errs = validate.Var(s, "hsla")
  5066. NotEqual(t, errs, nil)
  5067. AssertError(t, errs, "", "", "", "", "hsla")
  5068. s = "hsla(360,101%,50%)"
  5069. errs = validate.Var(s, "hsla")
  5070. NotEqual(t, errs, nil)
  5071. AssertError(t, errs, "", "", "", "", "hsla")
  5072. s = "hsla(360,100%,101%)"
  5073. errs = validate.Var(s, "hsla")
  5074. NotEqual(t, errs, nil)
  5075. AssertError(t, errs, "", "", "", "", "hsla")
  5076. i := 1
  5077. validate.Var(i, "hsla")
  5078. NotEqual(t, errs, nil)
  5079. AssertError(t, errs, "", "", "", "", "hsla")
  5080. }
  5081. func TestHsl(t *testing.T) {
  5082. validate := New()
  5083. s := "hsl(360,100%,50%)"
  5084. errs := validate.Var(s, "hsl")
  5085. Equal(t, errs, nil)
  5086. s = "hsl(0,0%,0%)"
  5087. errs = validate.Var(s, "hsl")
  5088. Equal(t, errs, nil)
  5089. s = "hsl(361,100%,50%)"
  5090. errs = validate.Var(s, "hsl")
  5091. NotEqual(t, errs, nil)
  5092. AssertError(t, errs, "", "", "", "", "hsl")
  5093. s = "hsl(361,101%,50%)"
  5094. errs = validate.Var(s, "hsl")
  5095. NotEqual(t, errs, nil)
  5096. AssertError(t, errs, "", "", "", "", "hsl")
  5097. s = "hsl(361,100%,101%)"
  5098. errs = validate.Var(s, "hsl")
  5099. NotEqual(t, errs, nil)
  5100. AssertError(t, errs, "", "", "", "", "hsl")
  5101. s = "hsl(-10,100%,100%)"
  5102. errs = validate.Var(s, "hsl")
  5103. NotEqual(t, errs, nil)
  5104. AssertError(t, errs, "", "", "", "", "hsl")
  5105. i := 1
  5106. errs = validate.Var(i, "hsl")
  5107. NotEqual(t, errs, nil)
  5108. AssertError(t, errs, "", "", "", "", "hsl")
  5109. }
  5110. func TestRgba(t *testing.T) {
  5111. validate := New()
  5112. s := "rgba(0,31,255,0.5)"
  5113. errs := validate.Var(s, "rgba")
  5114. Equal(t, errs, nil)
  5115. s = "rgba(0,31,255,0.12)"
  5116. errs = validate.Var(s, "rgba")
  5117. Equal(t, errs, nil)
  5118. s = "rgba(12%,55%,100%,0.12)"
  5119. errs = validate.Var(s, "rgba")
  5120. Equal(t, errs, nil)
  5121. s = "rgba( 0, 31, 255, 0.5)"
  5122. errs = validate.Var(s, "rgba")
  5123. Equal(t, errs, nil)
  5124. s = "rgba(12%,55,100%,0.12)"
  5125. errs = validate.Var(s, "rgba")
  5126. NotEqual(t, errs, nil)
  5127. AssertError(t, errs, "", "", "", "", "rgba")
  5128. s = "rgb(0, 31, 255)"
  5129. errs = validate.Var(s, "rgba")
  5130. NotEqual(t, errs, nil)
  5131. AssertError(t, errs, "", "", "", "", "rgba")
  5132. s = "rgb(1,349,275,0.5)"
  5133. errs = validate.Var(s, "rgba")
  5134. NotEqual(t, errs, nil)
  5135. AssertError(t, errs, "", "", "", "", "rgba")
  5136. s = "rgb(01,31,255,0.5)"
  5137. errs = validate.Var(s, "rgba")
  5138. NotEqual(t, errs, nil)
  5139. AssertError(t, errs, "", "", "", "", "rgba")
  5140. i := 1
  5141. errs = validate.Var(i, "rgba")
  5142. NotEqual(t, errs, nil)
  5143. AssertError(t, errs, "", "", "", "", "rgba")
  5144. }
  5145. func TestRgb(t *testing.T) {
  5146. validate := New()
  5147. s := "rgb(0,31,255)"
  5148. errs := validate.Var(s, "rgb")
  5149. Equal(t, errs, nil)
  5150. s = "rgb(0, 31, 255)"
  5151. errs = validate.Var(s, "rgb")
  5152. Equal(t, errs, nil)
  5153. s = "rgb(10%, 50%, 100%)"
  5154. errs = validate.Var(s, "rgb")
  5155. Equal(t, errs, nil)
  5156. s = "rgb(10%, 50%, 55)"
  5157. errs = validate.Var(s, "rgb")
  5158. NotEqual(t, errs, nil)
  5159. AssertError(t, errs, "", "", "", "", "rgb")
  5160. s = "rgb(1,349,275)"
  5161. errs = validate.Var(s, "rgb")
  5162. NotEqual(t, errs, nil)
  5163. AssertError(t, errs, "", "", "", "", "rgb")
  5164. s = "rgb(01,31,255)"
  5165. errs = validate.Var(s, "rgb")
  5166. NotEqual(t, errs, nil)
  5167. AssertError(t, errs, "", "", "", "", "rgb")
  5168. s = "rgba(0,31,255)"
  5169. errs = validate.Var(s, "rgb")
  5170. NotEqual(t, errs, nil)
  5171. AssertError(t, errs, "", "", "", "", "rgb")
  5172. i := 1
  5173. errs = validate.Var(i, "rgb")
  5174. NotEqual(t, errs, nil)
  5175. AssertError(t, errs, "", "", "", "", "rgb")
  5176. }
  5177. func TestEmail(t *testing.T) {
  5178. validate := New()
  5179. s := "test@mail.com"
  5180. errs := validate.Var(s, "email")
  5181. Equal(t, errs, nil)
  5182. s = "Dörte@Sörensen.example.com"
  5183. errs = validate.Var(s, "email")
  5184. Equal(t, errs, nil)
  5185. s = "θσερ@εχαμπλε.ψομ"
  5186. errs = validate.Var(s, "email")
  5187. Equal(t, errs, nil)
  5188. s = "юзер@екзампл.ком"
  5189. errs = validate.Var(s, "email")
  5190. Equal(t, errs, nil)
  5191. s = "उपयोगकर्ता@उदाहरण.कॉम"
  5192. errs = validate.Var(s, "email")
  5193. Equal(t, errs, nil)
  5194. s = "用户@例子.广告"
  5195. errs = validate.Var(s, "email")
  5196. Equal(t, errs, nil)
  5197. s = "mail@domain_with_underscores.org"
  5198. errs = validate.Var(s, "email")
  5199. NotEqual(t, errs, nil)
  5200. AssertError(t, errs, "", "", "", "", "email")
  5201. s = ""
  5202. errs = validate.Var(s, "email")
  5203. NotEqual(t, errs, nil)
  5204. AssertError(t, errs, "", "", "", "", "email")
  5205. s = "test@email"
  5206. errs = validate.Var(s, "email")
  5207. NotEqual(t, errs, nil)
  5208. AssertError(t, errs, "", "", "", "", "email")
  5209. s = "test@email."
  5210. errs = validate.Var(s, "email")
  5211. NotEqual(t, errs, nil)
  5212. AssertError(t, errs, "", "", "", "", "email")
  5213. s = "@email.com"
  5214. errs = validate.Var(s, "email")
  5215. NotEqual(t, errs, nil)
  5216. AssertError(t, errs, "", "", "", "", "email")
  5217. s = `"test test"@email.com`
  5218. errs = validate.Var(s, "email")
  5219. Equal(t, errs, nil)
  5220. s = `"@email.com`
  5221. errs = validate.Var(s, "email")
  5222. NotEqual(t, errs, nil)
  5223. AssertError(t, errs, "", "", "", "", "email")
  5224. i := true
  5225. errs = validate.Var(i, "email")
  5226. NotEqual(t, errs, nil)
  5227. AssertError(t, errs, "", "", "", "", "email")
  5228. }
  5229. func TestHexColor(t *testing.T) {
  5230. validate := New()
  5231. s := "#fff"
  5232. errs := validate.Var(s, "hexcolor")
  5233. Equal(t, errs, nil)
  5234. s = "#c2c2c2"
  5235. errs = validate.Var(s, "hexcolor")
  5236. Equal(t, errs, nil)
  5237. s = "fff"
  5238. errs = validate.Var(s, "hexcolor")
  5239. NotEqual(t, errs, nil)
  5240. AssertError(t, errs, "", "", "", "", "hexcolor")
  5241. s = "fffFF"
  5242. errs = validate.Var(s, "hexcolor")
  5243. NotEqual(t, errs, nil)
  5244. AssertError(t, errs, "", "", "", "", "hexcolor")
  5245. i := true
  5246. errs = validate.Var(i, "hexcolor")
  5247. NotEqual(t, errs, nil)
  5248. AssertError(t, errs, "", "", "", "", "hexcolor")
  5249. }
  5250. func TestHexadecimal(t *testing.T) {
  5251. validate := New()
  5252. s := "ff0044"
  5253. errs := validate.Var(s, "hexadecimal")
  5254. Equal(t, errs, nil)
  5255. s = "abcdefg"
  5256. errs = validate.Var(s, "hexadecimal")
  5257. NotEqual(t, errs, nil)
  5258. AssertError(t, errs, "", "", "", "", "hexadecimal")
  5259. i := true
  5260. errs = validate.Var(i, "hexadecimal")
  5261. NotEqual(t, errs, nil)
  5262. AssertError(t, errs, "", "", "", "", "hexadecimal")
  5263. }
  5264. func TestNumber(t *testing.T) {
  5265. validate := New()
  5266. s := "1"
  5267. errs := validate.Var(s, "number")
  5268. Equal(t, errs, nil)
  5269. s = "+1"
  5270. errs = validate.Var(s, "number")
  5271. NotEqual(t, errs, nil)
  5272. AssertError(t, errs, "", "", "", "", "number")
  5273. s = "-1"
  5274. errs = validate.Var(s, "number")
  5275. NotEqual(t, errs, nil)
  5276. AssertError(t, errs, "", "", "", "", "number")
  5277. s = "1.12"
  5278. errs = validate.Var(s, "number")
  5279. NotEqual(t, errs, nil)
  5280. AssertError(t, errs, "", "", "", "", "number")
  5281. s = "+1.12"
  5282. errs = validate.Var(s, "number")
  5283. NotEqual(t, errs, nil)
  5284. AssertError(t, errs, "", "", "", "", "number")
  5285. s = "-1.12"
  5286. errs = validate.Var(s, "number")
  5287. NotEqual(t, errs, nil)
  5288. AssertError(t, errs, "", "", "", "", "number")
  5289. s = "1."
  5290. errs = validate.Var(s, "number")
  5291. NotEqual(t, errs, nil)
  5292. AssertError(t, errs, "", "", "", "", "number")
  5293. s = "1.o"
  5294. errs = validate.Var(s, "number")
  5295. NotEqual(t, errs, nil)
  5296. AssertError(t, errs, "", "", "", "", "number")
  5297. i := 1
  5298. errs = validate.Var(i, "number")
  5299. Equal(t, errs, nil)
  5300. }
  5301. func TestNumeric(t *testing.T) {
  5302. validate := New()
  5303. s := "1"
  5304. errs := validate.Var(s, "numeric")
  5305. Equal(t, errs, nil)
  5306. s = "+1"
  5307. errs = validate.Var(s, "numeric")
  5308. Equal(t, errs, nil)
  5309. s = "-1"
  5310. errs = validate.Var(s, "numeric")
  5311. Equal(t, errs, nil)
  5312. s = "1.12"
  5313. errs = validate.Var(s, "numeric")
  5314. Equal(t, errs, nil)
  5315. s = "+1.12"
  5316. errs = validate.Var(s, "numeric")
  5317. Equal(t, errs, nil)
  5318. s = "-1.12"
  5319. errs = validate.Var(s, "numeric")
  5320. Equal(t, errs, nil)
  5321. s = "1."
  5322. errs = validate.Var(s, "numeric")
  5323. NotEqual(t, errs, nil)
  5324. AssertError(t, errs, "", "", "", "", "numeric")
  5325. s = "1.o"
  5326. errs = validate.Var(s, "numeric")
  5327. NotEqual(t, errs, nil)
  5328. AssertError(t, errs, "", "", "", "", "numeric")
  5329. i := 1
  5330. errs = validate.Var(i, "numeric")
  5331. Equal(t, errs, nil)
  5332. }
  5333. func TestAlphaNumeric(t *testing.T) {
  5334. validate := New()
  5335. s := "abcd123"
  5336. errs := validate.Var(s, "alphanum")
  5337. Equal(t, errs, nil)
  5338. s = "abc!23"
  5339. errs = validate.Var(s, "alphanum")
  5340. NotEqual(t, errs, nil)
  5341. AssertError(t, errs, "", "", "", "", "alphanum")
  5342. errs = validate.Var(1, "alphanum")
  5343. NotEqual(t, errs, nil)
  5344. AssertError(t, errs, "", "", "", "", "alphanum")
  5345. }
  5346. func TestAlpha(t *testing.T) {
  5347. validate := New()
  5348. s := "abcd"
  5349. errs := validate.Var(s, "alpha")
  5350. Equal(t, errs, nil)
  5351. s = "abc®"
  5352. errs = validate.Var(s, "alpha")
  5353. NotEqual(t, errs, nil)
  5354. AssertError(t, errs, "", "", "", "", "alpha")
  5355. s = "abc÷"
  5356. errs = validate.Var(s, "alpha")
  5357. NotEqual(t, errs, nil)
  5358. AssertError(t, errs, "", "", "", "", "alpha")
  5359. s = "abc1"
  5360. errs = validate.Var(s, "alpha")
  5361. NotEqual(t, errs, nil)
  5362. AssertError(t, errs, "", "", "", "", "alpha")
  5363. s = "this is a test string"
  5364. errs = validate.Var(s, "alpha")
  5365. NotEqual(t, errs, nil)
  5366. AssertError(t, errs, "", "", "", "", "alpha")
  5367. errs = validate.Var(1, "alpha")
  5368. NotEqual(t, errs, nil)
  5369. AssertError(t, errs, "", "", "", "", "alpha")
  5370. }
  5371. func TestStructStringValidation(t *testing.T) {
  5372. validate := New()
  5373. tSuccess := &TestString{
  5374. Required: "Required",
  5375. Len: "length==10",
  5376. Min: "min=1",
  5377. Max: "1234567890",
  5378. MinMax: "12345",
  5379. Lt: "012345678",
  5380. Lte: "0123456789",
  5381. Gt: "01234567890",
  5382. Gte: "0123456789",
  5383. OmitEmpty: "",
  5384. Sub: &SubTest{
  5385. Test: "1",
  5386. },
  5387. SubIgnore: &SubTest{
  5388. Test: "",
  5389. },
  5390. Anonymous: struct {
  5391. A string `validate:"required"`
  5392. }{
  5393. A: "1",
  5394. },
  5395. Iface: &Impl{
  5396. F: "123",
  5397. },
  5398. }
  5399. errs := validate.Struct(tSuccess)
  5400. Equal(t, errs, nil)
  5401. tFail := &TestString{
  5402. Required: "",
  5403. Len: "",
  5404. Min: "",
  5405. Max: "12345678901",
  5406. MinMax: "",
  5407. Lt: "0123456789",
  5408. Lte: "01234567890",
  5409. Gt: "1",
  5410. Gte: "1",
  5411. OmitEmpty: "12345678901",
  5412. Sub: &SubTest{
  5413. Test: "",
  5414. },
  5415. Anonymous: struct {
  5416. A string `validate:"required"`
  5417. }{
  5418. A: "",
  5419. },
  5420. Iface: &Impl{
  5421. F: "12",
  5422. },
  5423. }
  5424. errs = validate.Struct(tFail)
  5425. // Assert Top Level
  5426. NotEqual(t, errs, nil)
  5427. Equal(t, len(errs.(ValidationErrors)), 13)
  5428. // Assert Fields
  5429. AssertError(t, errs, "TestString.Required", "TestString.Required", "Required", "Required", "required")
  5430. AssertError(t, errs, "TestString.Len", "TestString.Len", "Len", "Len", "len")
  5431. AssertError(t, errs, "TestString.Min", "TestString.Min", "Min", "Min", "min")
  5432. AssertError(t, errs, "TestString.Max", "TestString.Max", "Max", "Max", "max")
  5433. AssertError(t, errs, "TestString.MinMax", "TestString.MinMax", "MinMax", "MinMax", "min")
  5434. AssertError(t, errs, "TestString.Lt", "TestString.Lt", "Lt", "Lt", "lt")
  5435. AssertError(t, errs, "TestString.Lte", "TestString.Lte", "Lte", "Lte", "lte")
  5436. AssertError(t, errs, "TestString.Gt", "TestString.Gt", "Gt", "Gt", "gt")
  5437. AssertError(t, errs, "TestString.Gte", "TestString.Gte", "Gte", "Gte", "gte")
  5438. AssertError(t, errs, "TestString.OmitEmpty", "TestString.OmitEmpty", "OmitEmpty", "OmitEmpty", "max")
  5439. // Nested Struct Field Errs
  5440. AssertError(t, errs, "TestString.Anonymous.A", "TestString.Anonymous.A", "A", "A", "required")
  5441. AssertError(t, errs, "TestString.Sub.Test", "TestString.Sub.Test", "Test", "Test", "required")
  5442. AssertError(t, errs, "TestString.Iface.F", "TestString.Iface.F", "F", "F", "len")
  5443. }
  5444. func TestStructInt32Validation(t *testing.T) {
  5445. type TestInt32 struct {
  5446. Required int `validate:"required"`
  5447. Len int `validate:"len=10"`
  5448. Min int `validate:"min=1"`
  5449. Max int `validate:"max=10"`
  5450. MinMax int `validate:"min=1,max=10"`
  5451. Lt int `validate:"lt=10"`
  5452. Lte int `validate:"lte=10"`
  5453. Gt int `validate:"gt=10"`
  5454. Gte int `validate:"gte=10"`
  5455. OmitEmpty int `validate:"omitempty,min=1,max=10"`
  5456. }
  5457. tSuccess := &TestInt32{
  5458. Required: 1,
  5459. Len: 10,
  5460. Min: 1,
  5461. Max: 10,
  5462. MinMax: 5,
  5463. Lt: 9,
  5464. Lte: 10,
  5465. Gt: 11,
  5466. Gte: 10,
  5467. OmitEmpty: 0,
  5468. }
  5469. validate := New()
  5470. errs := validate.Struct(tSuccess)
  5471. Equal(t, errs, nil)
  5472. tFail := &TestInt32{
  5473. Required: 0,
  5474. Len: 11,
  5475. Min: -1,
  5476. Max: 11,
  5477. MinMax: -1,
  5478. Lt: 10,
  5479. Lte: 11,
  5480. Gt: 10,
  5481. Gte: 9,
  5482. OmitEmpty: 11,
  5483. }
  5484. errs = validate.Struct(tFail)
  5485. // Assert Top Level
  5486. NotEqual(t, errs, nil)
  5487. Equal(t, len(errs.(ValidationErrors)), 10)
  5488. // Assert Fields
  5489. AssertError(t, errs, "TestInt32.Required", "TestInt32.Required", "Required", "Required", "required")
  5490. AssertError(t, errs, "TestInt32.Len", "TestInt32.Len", "Len", "Len", "len")
  5491. AssertError(t, errs, "TestInt32.Min", "TestInt32.Min", "Min", "Min", "min")
  5492. AssertError(t, errs, "TestInt32.Max", "TestInt32.Max", "Max", "Max", "max")
  5493. AssertError(t, errs, "TestInt32.MinMax", "TestInt32.MinMax", "MinMax", "MinMax", "min")
  5494. AssertError(t, errs, "TestInt32.Lt", "TestInt32.Lt", "Lt", "Lt", "lt")
  5495. AssertError(t, errs, "TestInt32.Lte", "TestInt32.Lte", "Lte", "Lte", "lte")
  5496. AssertError(t, errs, "TestInt32.Gt", "TestInt32.Gt", "Gt", "Gt", "gt")
  5497. AssertError(t, errs, "TestInt32.Gte", "TestInt32.Gte", "Gte", "Gte", "gte")
  5498. AssertError(t, errs, "TestInt32.OmitEmpty", "TestInt32.OmitEmpty", "OmitEmpty", "OmitEmpty", "max")
  5499. }
  5500. func TestStructUint64Validation(t *testing.T) {
  5501. validate := New()
  5502. tSuccess := &TestUint64{
  5503. Required: 1,
  5504. Len: 10,
  5505. Min: 1,
  5506. Max: 10,
  5507. MinMax: 5,
  5508. OmitEmpty: 0,
  5509. }
  5510. errs := validate.Struct(tSuccess)
  5511. Equal(t, errs, nil)
  5512. tFail := &TestUint64{
  5513. Required: 0,
  5514. Len: 11,
  5515. Min: 0,
  5516. Max: 11,
  5517. MinMax: 0,
  5518. OmitEmpty: 11,
  5519. }
  5520. errs = validate.Struct(tFail)
  5521. // Assert Top Level
  5522. NotEqual(t, errs, nil)
  5523. Equal(t, len(errs.(ValidationErrors)), 6)
  5524. // Assert Fields
  5525. AssertError(t, errs, "TestUint64.Required", "TestUint64.Required", "Required", "Required", "required")
  5526. AssertError(t, errs, "TestUint64.Len", "TestUint64.Len", "Len", "Len", "len")
  5527. AssertError(t, errs, "TestUint64.Min", "TestUint64.Min", "Min", "Min", "min")
  5528. AssertError(t, errs, "TestUint64.Max", "TestUint64.Max", "Max", "Max", "max")
  5529. AssertError(t, errs, "TestUint64.MinMax", "TestUint64.MinMax", "MinMax", "MinMax", "min")
  5530. AssertError(t, errs, "TestUint64.OmitEmpty", "TestUint64.OmitEmpty", "OmitEmpty", "OmitEmpty", "max")
  5531. }
  5532. func TestStructFloat64Validation(t *testing.T) {
  5533. validate := New()
  5534. tSuccess := &TestFloat64{
  5535. Required: 1,
  5536. Len: 10,
  5537. Min: 1,
  5538. Max: 10,
  5539. MinMax: 5,
  5540. OmitEmpty: 0,
  5541. }
  5542. errs := validate.Struct(tSuccess)
  5543. Equal(t, errs, nil)
  5544. tFail := &TestFloat64{
  5545. Required: 0,
  5546. Len: 11,
  5547. Min: 0,
  5548. Max: 11,
  5549. MinMax: 0,
  5550. OmitEmpty: 11,
  5551. }
  5552. errs = validate.Struct(tFail)
  5553. // Assert Top Level
  5554. NotEqual(t, errs, nil)
  5555. Equal(t, len(errs.(ValidationErrors)), 6)
  5556. // Assert Fields
  5557. AssertError(t, errs, "TestFloat64.Required", "TestFloat64.Required", "Required", "Required", "required")
  5558. AssertError(t, errs, "TestFloat64.Len", "TestFloat64.Len", "Len", "Len", "len")
  5559. AssertError(t, errs, "TestFloat64.Min", "TestFloat64.Min", "Min", "Min", "min")
  5560. AssertError(t, errs, "TestFloat64.Max", "TestFloat64.Max", "Max", "Max", "max")
  5561. AssertError(t, errs, "TestFloat64.MinMax", "TestFloat64.MinMax", "MinMax", "MinMax", "min")
  5562. AssertError(t, errs, "TestFloat64.OmitEmpty", "TestFloat64.OmitEmpty", "OmitEmpty", "OmitEmpty", "max")
  5563. }
  5564. func TestStructSliceValidation(t *testing.T) {
  5565. validate := New()
  5566. tSuccess := &TestSlice{
  5567. Required: []int{1},
  5568. Len: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0},
  5569. Min: []int{1, 2},
  5570. Max: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0},
  5571. MinMax: []int{1, 2, 3, 4, 5},
  5572. OmitEmpty: nil,
  5573. }
  5574. errs := validate.Struct(tSuccess)
  5575. Equal(t, errs, nil)
  5576. tFail := &TestSlice{
  5577. Required: nil,
  5578. Len: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1},
  5579. Min: []int{},
  5580. Max: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1},
  5581. MinMax: []int{},
  5582. OmitEmpty: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1},
  5583. }
  5584. errs = validate.Struct(tFail)
  5585. NotEqual(t, errs, nil)
  5586. Equal(t, len(errs.(ValidationErrors)), 6)
  5587. // Assert Field Errors
  5588. AssertError(t, errs, "TestSlice.Required", "TestSlice.Required", "Required", "Required", "required")
  5589. AssertError(t, errs, "TestSlice.Len", "TestSlice.Len", "Len", "Len", "len")
  5590. AssertError(t, errs, "TestSlice.Min", "TestSlice.Min", "Min", "Min", "min")
  5591. AssertError(t, errs, "TestSlice.Max", "TestSlice.Max", "Max", "Max", "max")
  5592. AssertError(t, errs, "TestSlice.MinMax", "TestSlice.MinMax", "MinMax", "MinMax", "min")
  5593. AssertError(t, errs, "TestSlice.OmitEmpty", "TestSlice.OmitEmpty", "OmitEmpty", "OmitEmpty", "max")
  5594. fe := getError(errs, "TestSlice.Len", "TestSlice.Len")
  5595. NotEqual(t, fe, nil)
  5596. Equal(t, fe.Field(), "Len")
  5597. Equal(t, fe.StructField(), "Len")
  5598. Equal(t, fe.Namespace(), "TestSlice.Len")
  5599. Equal(t, fe.StructNamespace(), "TestSlice.Len")
  5600. Equal(t, fe.Tag(), "len")
  5601. Equal(t, fe.ActualTag(), "len")
  5602. Equal(t, fe.Param(), "10")
  5603. Equal(t, fe.Kind(), reflect.Slice)
  5604. Equal(t, fe.Type(), reflect.TypeOf([]int{}))
  5605. _, ok := fe.Value().([]int)
  5606. Equal(t, ok, true)
  5607. }
  5608. func TestInvalidStruct(t *testing.T) {
  5609. validate := New()
  5610. s := &SubTest{
  5611. Test: "1",
  5612. }
  5613. err := validate.Struct(s.Test)
  5614. NotEqual(t, err, nil)
  5615. Equal(t, err.Error(), "validator: (nil string)")
  5616. err = validate.Struct(nil)
  5617. NotEqual(t, err, nil)
  5618. Equal(t, err.Error(), "validator: (nil)")
  5619. err = validate.StructPartial(nil, "SubTest.Test")
  5620. NotEqual(t, err, nil)
  5621. Equal(t, err.Error(), "validator: (nil)")
  5622. err = validate.StructExcept(nil, "SubTest.Test")
  5623. NotEqual(t, err, nil)
  5624. Equal(t, err.Error(), "validator: (nil)")
  5625. }
  5626. func TestInvalidValidatorFunction(t *testing.T) {
  5627. validate := New()
  5628. s := &SubTest{
  5629. Test: "1",
  5630. }
  5631. PanicMatches(t, func() { validate.Var(s.Test, "zzxxBadFunction") }, "Undefined validation function 'zzxxBadFunction' on field ''")
  5632. }
  5633. func TestCustomFieldName(t *testing.T) {
  5634. validate := New()
  5635. validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
  5636. name := strings.SplitN(fld.Tag.Get("schema"), ",", 2)[0]
  5637. if name == "-" {
  5638. return ""
  5639. }
  5640. return name
  5641. })
  5642. type A struct {
  5643. B string `schema:"b" validate:"required"`
  5644. C string `schema:"c" validate:"required"`
  5645. D []bool `schema:"d" validate:"required"`
  5646. E string `schema:"-" validate:"required"`
  5647. }
  5648. a := &A{}
  5649. err := validate.Struct(a)
  5650. NotEqual(t, err, nil)
  5651. errs := err.(ValidationErrors)
  5652. Equal(t, len(errs), 4)
  5653. Equal(t, getError(errs, "A.b", "A.B").Field(), "b")
  5654. Equal(t, getError(errs, "A.c", "A.C").Field(), "c")
  5655. Equal(t, getError(errs, "A.d", "A.D").Field(), "d")
  5656. Equal(t, getError(errs, "A.E", "A.E").Field(), "E")
  5657. v2 := New()
  5658. err = v2.Struct(a)
  5659. NotEqual(t, err, nil)
  5660. errs = err.(ValidationErrors)
  5661. Equal(t, len(errs), 4)
  5662. Equal(t, getError(errs, "A.B", "A.B").Field(), "B")
  5663. Equal(t, getError(errs, "A.C", "A.C").Field(), "C")
  5664. Equal(t, getError(errs, "A.D", "A.D").Field(), "D")
  5665. Equal(t, getError(errs, "A.E", "A.E").Field(), "E")
  5666. }
  5667. func TestMutipleRecursiveExtractStructCache(t *testing.T) {
  5668. validate := New()
  5669. type Recursive struct {
  5670. Field *string `validate:"required,len=5,ne=string"`
  5671. }
  5672. var test Recursive
  5673. current := reflect.ValueOf(test)
  5674. name := "Recursive"
  5675. proceed := make(chan struct{})
  5676. sc := validate.extractStructCache(current, name)
  5677. ptr := fmt.Sprintf("%p", sc)
  5678. for i := 0; i < 100; i++ {
  5679. go func() {
  5680. <-proceed
  5681. sc := validate.extractStructCache(current, name)
  5682. Equal(t, ptr, fmt.Sprintf("%p", sc))
  5683. }()
  5684. }
  5685. close(proceed)
  5686. }
  5687. // Thanks @robbrockbank, see https://github.com/go-playground/validator/issues/249
  5688. func TestPointerAndOmitEmpty(t *testing.T) {
  5689. validate := New()
  5690. type Test struct {
  5691. MyInt *int `validate:"omitempty,gte=2,lte=255"`
  5692. }
  5693. val1 := 0
  5694. val2 := 256
  5695. t1 := Test{MyInt: &val1} // This should fail validation on gte because value is 0
  5696. t2 := Test{MyInt: &val2} // This should fail validate on lte because value is 256
  5697. t3 := Test{MyInt: nil} // This should succeed validation because pointer is nil
  5698. errs := validate.Struct(t1)
  5699. NotEqual(t, errs, nil)
  5700. AssertError(t, errs, "Test.MyInt", "Test.MyInt", "MyInt", "MyInt", "gte")
  5701. errs = validate.Struct(t2)
  5702. NotEqual(t, errs, nil)
  5703. AssertError(t, errs, "Test.MyInt", "Test.MyInt", "MyInt", "MyInt", "lte")
  5704. errs = validate.Struct(t3)
  5705. Equal(t, errs, nil)
  5706. type TestIface struct {
  5707. MyInt interface{} `validate:"omitempty,gte=2,lte=255"`
  5708. }
  5709. ti1 := TestIface{MyInt: &val1} // This should fail validation on gte because value is 0
  5710. ti2 := TestIface{MyInt: &val2} // This should fail validate on lte because value is 256
  5711. ti3 := TestIface{MyInt: nil} // This should succeed validation because pointer is nil
  5712. errs = validate.Struct(ti1)
  5713. NotEqual(t, errs, nil)
  5714. AssertError(t, errs, "TestIface.MyInt", "TestIface.MyInt", "MyInt", "MyInt", "gte")
  5715. errs = validate.Struct(ti2)
  5716. NotEqual(t, errs, nil)
  5717. AssertError(t, errs, "TestIface.MyInt", "TestIface.MyInt", "MyInt", "MyInt", "lte")
  5718. errs = validate.Struct(ti3)
  5719. Equal(t, errs, nil)
  5720. }
  5721. func TestRequired(t *testing.T) {
  5722. validate := New()
  5723. validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
  5724. name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
  5725. if name == "-" {
  5726. return ""
  5727. }
  5728. return name
  5729. })
  5730. type Test struct {
  5731. Value interface{} `validate:"required"`
  5732. }
  5733. var test Test
  5734. err := validate.Struct(test)
  5735. NotEqual(t, err, nil)
  5736. AssertError(t, err.(ValidationErrors), "Test.Value", "Test.Value", "Value", "Value", "required")
  5737. }
  5738. func TestTranslations(t *testing.T) {
  5739. en := en.New()
  5740. uni := ut.New(en, en, fr.New())
  5741. trans, _ := uni.GetTranslator("en")
  5742. fr, _ := uni.GetTranslator("fr")
  5743. validate := New()
  5744. err := validate.RegisterTranslation("required", trans,
  5745. func(ut ut.Translator) (err error) {
  5746. // using this stype because multiple translation may have to be added for the full translation
  5747. if err = ut.Add("required", "{0} is a required field", false); err != nil {
  5748. return
  5749. }
  5750. return
  5751. }, func(ut ut.Translator, fe FieldError) string {
  5752. t, err := ut.T(fe.Tag(), fe.Field())
  5753. if err != nil {
  5754. fmt.Printf("warning: error translating FieldError: %#v", fe.(*fieldError))
  5755. return fe.(*fieldError).Error()
  5756. }
  5757. return t
  5758. })
  5759. Equal(t, err, nil)
  5760. err = validate.RegisterTranslation("required", fr,
  5761. func(ut ut.Translator) (err error) {
  5762. // using this stype because multiple translation may have to be added for the full translation
  5763. if err = ut.Add("required", "{0} est un champ obligatoire", false); err != nil {
  5764. return
  5765. }
  5766. return
  5767. }, func(ut ut.Translator, fe FieldError) string {
  5768. t, transErr := ut.T(fe.Tag(), fe.Field())
  5769. if transErr != nil {
  5770. fmt.Printf("warning: error translating FieldError: %#v", fe.(*fieldError))
  5771. return fe.(*fieldError).Error()
  5772. }
  5773. return t
  5774. })
  5775. Equal(t, err, nil)
  5776. type Test struct {
  5777. Value interface{} `validate:"required"`
  5778. }
  5779. var test Test
  5780. err = validate.Struct(test)
  5781. NotEqual(t, err, nil)
  5782. errs := err.(ValidationErrors)
  5783. Equal(t, len(errs), 1)
  5784. fe := errs[0]
  5785. Equal(t, fe.Tag(), "required")
  5786. Equal(t, fe.Namespace(), "Test.Value")
  5787. Equal(t, fe.Translate(trans), fmt.Sprintf("%s is a required field", fe.Field()))
  5788. Equal(t, fe.Translate(fr), fmt.Sprintf("%s est un champ obligatoire", fe.Field()))
  5789. nl := nl.New()
  5790. uni2 := ut.New(nl, nl)
  5791. trans2, _ := uni2.GetTranslator("nl")
  5792. Equal(t, fe.Translate(trans2), "Key: 'Test.Value' Error:Field validation for 'Value' failed on the 'required' tag")
  5793. terrs := errs.Translate(trans)
  5794. Equal(t, len(terrs), 1)
  5795. v, ok := terrs["Test.Value"]
  5796. Equal(t, ok, true)
  5797. Equal(t, v, fmt.Sprintf("%s is a required field", fe.Field()))
  5798. terrs = errs.Translate(fr)
  5799. Equal(t, len(terrs), 1)
  5800. v, ok = terrs["Test.Value"]
  5801. Equal(t, ok, true)
  5802. Equal(t, v, fmt.Sprintf("%s est un champ obligatoire", fe.Field()))
  5803. type Test2 struct {
  5804. Value string `validate:"gt=1"`
  5805. }
  5806. var t2 Test2
  5807. err = validate.Struct(t2)
  5808. NotEqual(t, err, nil)
  5809. errs = err.(ValidationErrors)
  5810. Equal(t, len(errs), 1)
  5811. fe = errs[0]
  5812. Equal(t, fe.Tag(), "gt")
  5813. Equal(t, fe.Namespace(), "Test2.Value")
  5814. Equal(t, fe.Translate(trans), "Key: 'Test2.Value' Error:Field validation for 'Value' failed on the 'gt' tag")
  5815. }
  5816. func TestTranslationErrors(t *testing.T) {
  5817. en := en.New()
  5818. uni := ut.New(en, en, fr.New())
  5819. trans, _ := uni.GetTranslator("en")
  5820. trans.Add("required", "{0} is a required field", false) // using translator outside of validator also
  5821. validate := New()
  5822. err := validate.RegisterTranslation("required", trans,
  5823. func(ut ut.Translator) (err error) {
  5824. // using this stype because multiple translation may have to be added for the full translation
  5825. if err = ut.Add("required", "{0} is a required field", false); err != nil {
  5826. return
  5827. }
  5828. return
  5829. }, func(ut ut.Translator, fe FieldError) string {
  5830. t, err := ut.T(fe.Tag(), fe.Field())
  5831. if err != nil {
  5832. fmt.Printf("warning: error translating FieldError: %#v", fe.(*fieldError))
  5833. return fe.(*fieldError).Error()
  5834. }
  5835. return t
  5836. })
  5837. NotEqual(t, err, nil)
  5838. Equal(t, err.Error(), "error: conflicting key 'required' rule 'Unknown' with text '{0} is a required field' for locale 'en', value being ignored")
  5839. }
  5840. func TestStructFiltered(t *testing.T) {
  5841. p1 := func(ns []byte) bool {
  5842. if bytes.HasSuffix(ns, []byte("NoTag")) || bytes.HasSuffix(ns, []byte("Required")) {
  5843. return false
  5844. }
  5845. return true
  5846. }
  5847. p2 := func(ns []byte) bool {
  5848. if bytes.HasSuffix(ns, []byte("SubSlice[0].Test")) ||
  5849. bytes.HasSuffix(ns, []byte("SubSlice[0]")) ||
  5850. bytes.HasSuffix(ns, []byte("SubSlice")) ||
  5851. bytes.HasSuffix(ns, []byte("Sub")) ||
  5852. bytes.HasSuffix(ns, []byte("SubIgnore")) ||
  5853. bytes.HasSuffix(ns, []byte("Anonymous")) ||
  5854. bytes.HasSuffix(ns, []byte("Anonymous.A")) {
  5855. return false
  5856. }
  5857. return true
  5858. }
  5859. p3 := func(ns []byte) bool {
  5860. return !bytes.HasSuffix(ns, []byte("SubTest.Test"))
  5861. }
  5862. // p4 := []string{
  5863. // "A",
  5864. // }
  5865. tPartial := &TestPartial{
  5866. NoTag: "NoTag",
  5867. Required: "Required",
  5868. SubSlice: []*SubTest{
  5869. {
  5870. Test: "Required",
  5871. },
  5872. {
  5873. Test: "Required",
  5874. },
  5875. },
  5876. Sub: &SubTest{
  5877. Test: "1",
  5878. },
  5879. SubIgnore: &SubTest{
  5880. Test: "",
  5881. },
  5882. Anonymous: struct {
  5883. A string `validate:"required"`
  5884. ASubSlice []*SubTest `validate:"required,dive"`
  5885. SubAnonStruct []struct {
  5886. Test string `validate:"required"`
  5887. OtherTest string `validate:"required"`
  5888. } `validate:"required,dive"`
  5889. }{
  5890. A: "1",
  5891. ASubSlice: []*SubTest{
  5892. {
  5893. Test: "Required",
  5894. },
  5895. {
  5896. Test: "Required",
  5897. },
  5898. },
  5899. SubAnonStruct: []struct {
  5900. Test string `validate:"required"`
  5901. OtherTest string `validate:"required"`
  5902. }{
  5903. {"Required", "RequiredOther"},
  5904. {"Required", "RequiredOther"},
  5905. },
  5906. },
  5907. }
  5908. validate := New()
  5909. // the following should all return no errors as everything is valid in
  5910. // the default state
  5911. errs := validate.StructFilteredCtx(context.Background(), tPartial, p1)
  5912. Equal(t, errs, nil)
  5913. errs = validate.StructFiltered(tPartial, p2)
  5914. Equal(t, errs, nil)
  5915. // this isn't really a robust test, but is ment to illustrate the ANON CASE below
  5916. errs = validate.StructFiltered(tPartial.SubSlice[0], p3)
  5917. Equal(t, errs, nil)
  5918. // mod tParial for required feild and re-test making sure invalid fields are NOT required:
  5919. tPartial.Required = ""
  5920. // inversion and retesting Partial to generate failures:
  5921. errs = validate.StructFiltered(tPartial, p1)
  5922. NotEqual(t, errs, nil)
  5923. AssertError(t, errs, "TestPartial.Required", "TestPartial.Required", "Required", "Required", "required")
  5924. // reset Required field, and set nested struct
  5925. tPartial.Required = "Required"
  5926. tPartial.Anonymous.A = ""
  5927. // will pass as unset feilds is not going to be tested
  5928. errs = validate.StructFiltered(tPartial, p1)
  5929. Equal(t, errs, nil)
  5930. // will fail as unset feild is tested
  5931. errs = validate.StructFiltered(tPartial, p2)
  5932. NotEqual(t, errs, nil)
  5933. AssertError(t, errs, "TestPartial.Anonymous.A", "TestPartial.Anonymous.A", "A", "A", "required")
  5934. // reset nested struct and unset struct in slice
  5935. tPartial.Anonymous.A = "Required"
  5936. tPartial.SubSlice[0].Test = ""
  5937. // these will pass as unset item is NOT tested
  5938. errs = validate.StructFiltered(tPartial, p1)
  5939. Equal(t, errs, nil)
  5940. errs = validate.StructFiltered(tPartial, p2)
  5941. NotEqual(t, errs, nil)
  5942. AssertError(t, errs, "TestPartial.SubSlice[0].Test", "TestPartial.SubSlice[0].Test", "Test", "Test", "required")
  5943. Equal(t, len(errs.(ValidationErrors)), 1)
  5944. // Unset second slice member concurrently to test dive behavior:
  5945. tPartial.SubSlice[1].Test = ""
  5946. errs = validate.StructFiltered(tPartial, p1)
  5947. Equal(t, errs, nil)
  5948. errs = validate.StructFiltered(tPartial, p2)
  5949. NotEqual(t, errs, nil)
  5950. Equal(t, len(errs.(ValidationErrors)), 1)
  5951. AssertError(t, errs, "TestPartial.SubSlice[0].Test", "TestPartial.SubSlice[0].Test", "Test", "Test", "required")
  5952. // reset struct in slice, and unset struct in slice in unset posistion
  5953. tPartial.SubSlice[0].Test = "Required"
  5954. // these will pass as the unset item is NOT tested
  5955. errs = validate.StructFiltered(tPartial, p1)
  5956. Equal(t, errs, nil)
  5957. errs = validate.StructFiltered(tPartial, p2)
  5958. Equal(t, errs, nil)
  5959. tPartial.SubSlice[1].Test = "Required"
  5960. tPartial.Anonymous.SubAnonStruct[0].Test = ""
  5961. // these will pass as the unset item is NOT tested
  5962. errs = validate.StructFiltered(tPartial, p1)
  5963. Equal(t, errs, nil)
  5964. errs = validate.StructFiltered(tPartial, p2)
  5965. Equal(t, errs, nil)
  5966. dt := time.Now()
  5967. err := validate.StructFiltered(&dt, func(ns []byte) bool { return true })
  5968. NotEqual(t, err, nil)
  5969. Equal(t, err.Error(), "validator: (nil *time.Time)")
  5970. }
  5971. func TestRequiredPtr(t *testing.T) {
  5972. type Test struct {
  5973. Bool *bool `validate:"required"`
  5974. }
  5975. validate := New()
  5976. f := false
  5977. test := Test{
  5978. Bool: &f,
  5979. }
  5980. err := validate.Struct(test)
  5981. Equal(t, err, nil)
  5982. tr := true
  5983. test.Bool = &tr
  5984. err = validate.Struct(test)
  5985. Equal(t, err, nil)
  5986. test.Bool = nil
  5987. err = validate.Struct(test)
  5988. NotEqual(t, err, nil)
  5989. errs, ok := err.(ValidationErrors)
  5990. Equal(t, ok, true)
  5991. Equal(t, len(errs), 1)
  5992. AssertError(t, errs, "Test.Bool", "Test.Bool", "Bool", "Bool", "required")
  5993. type Test2 struct {
  5994. Bool bool `validate:"required"`
  5995. }
  5996. var test2 Test2
  5997. err = validate.Struct(test2)
  5998. NotEqual(t, err, nil)
  5999. errs, ok = err.(ValidationErrors)
  6000. Equal(t, ok, true)
  6001. Equal(t, len(errs), 1)
  6002. AssertError(t, errs, "Test2.Bool", "Test2.Bool", "Bool", "Bool", "required")
  6003. test2.Bool = true
  6004. err = validate.Struct(test2)
  6005. Equal(t, err, nil)
  6006. type Test3 struct {
  6007. Arr []string `validate:"required"`
  6008. }
  6009. var test3 Test3
  6010. err = validate.Struct(test3)
  6011. NotEqual(t, err, nil)
  6012. errs, ok = err.(ValidationErrors)
  6013. Equal(t, ok, true)
  6014. Equal(t, len(errs), 1)
  6015. AssertError(t, errs, "Test3.Arr", "Test3.Arr", "Arr", "Arr", "required")
  6016. test3.Arr = make([]string, 0)
  6017. err = validate.Struct(test3)
  6018. Equal(t, err, nil)
  6019. type Test4 struct {
  6020. Arr *[]string `validate:"required"` // I know I know pointer to array, just making sure validation works as expected...
  6021. }
  6022. var test4 Test4
  6023. err = validate.Struct(test4)
  6024. NotEqual(t, err, nil)
  6025. errs, ok = err.(ValidationErrors)
  6026. Equal(t, ok, true)
  6027. Equal(t, len(errs), 1)
  6028. AssertError(t, errs, "Test4.Arr", "Test4.Arr", "Arr", "Arr", "required")
  6029. arr := make([]string, 0)
  6030. test4.Arr = &arr
  6031. err = validate.Struct(test4)
  6032. Equal(t, err, nil)
  6033. }
  6034. func TestAlphaUnicodeValidation(t *testing.T) {
  6035. tests := []struct {
  6036. param string
  6037. expected bool
  6038. }{
  6039. {"", false},
  6040. {"abc", true},
  6041. {"this is a test string", false},
  6042. {"这是一个测试字符串", true},
  6043. {"123", false},
  6044. {"<>@;.-=", false},
  6045. {"ひらがな・カタカナ、.漢字", false},
  6046. {"あいうえおfoobar", true},
  6047. {"test@example.com", false},
  6048. {"1234abcDE", false},
  6049. {"カタカナ", true},
  6050. }
  6051. validate := New()
  6052. for i, test := range tests {
  6053. errs := validate.Var(test.param, "alphaunicode")
  6054. if test.expected {
  6055. if !IsEqual(errs, nil) {
  6056. t.Fatalf("Index: %d Alpha Unicode failed Error: %s", i, errs)
  6057. }
  6058. } else {
  6059. if IsEqual(errs, nil) {
  6060. t.Fatalf("Index: %d Alpha Unicode failed Error: %s", i, errs)
  6061. } else {
  6062. val := getError(errs, "", "")
  6063. if val.Tag() != "alphaunicode" {
  6064. t.Fatalf("Index: %d Alpha Unicode failed Error: %s", i, errs)
  6065. }
  6066. }
  6067. }
  6068. }
  6069. }
  6070. func TestAlphanumericUnicodeValidation(t *testing.T) {
  6071. tests := []struct {
  6072. param string
  6073. expected bool
  6074. }{
  6075. {"", false},
  6076. {"abc", true},
  6077. {"this is a test string", false},
  6078. {"这是一个测试字符串", true},
  6079. {"\u0031\u0032\u0033", true}, // unicode 5
  6080. {"123", true},
  6081. {"<>@;.-=", false},
  6082. {"ひらがな・カタカナ、.漢字", false},
  6083. {"あいうえおfoobar", true},
  6084. {"test@example.com", false},
  6085. {"1234abcDE", true},
  6086. {"カタカナ", true},
  6087. }
  6088. validate := New()
  6089. for i, test := range tests {
  6090. errs := validate.Var(test.param, "alphanumunicode")
  6091. if test.expected {
  6092. if !IsEqual(errs, nil) {
  6093. t.Fatalf("Index: %d Alphanum Unicode failed Error: %s", i, errs)
  6094. }
  6095. } else {
  6096. if IsEqual(errs, nil) {
  6097. t.Fatalf("Index: %d Alphanum Unicode failed Error: %s", i, errs)
  6098. } else {
  6099. val := getError(errs, "", "")
  6100. if val.Tag() != "alphanumunicode" {
  6101. t.Fatalf("Index: %d Alphanum Unicode failed Error: %s", i, errs)
  6102. }
  6103. }
  6104. }
  6105. }
  6106. }
  6107. func TestArrayStructNamespace(t *testing.T) {
  6108. validate := New()
  6109. validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
  6110. name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
  6111. if name == "-" {
  6112. return ""
  6113. }
  6114. return name
  6115. })
  6116. type child struct {
  6117. Name string `json:"name" validate:"required"`
  6118. }
  6119. var input struct {
  6120. Children []child `json:"children" validate:"required,gt=0,dive"`
  6121. }
  6122. input.Children = []child{{"ok"}, {""}}
  6123. errs := validate.Struct(input)
  6124. NotEqual(t, errs, nil)
  6125. ve := errs.(ValidationErrors)
  6126. Equal(t, len(ve), 1)
  6127. AssertError(t, errs, "children[1].name", "Children[1].Name", "name", "Name", "required")
  6128. }
  6129. func TestMapStructNamespace(t *testing.T) {
  6130. validate := New()
  6131. validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
  6132. name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
  6133. if name == "-" {
  6134. return ""
  6135. }
  6136. return name
  6137. })
  6138. type child struct {
  6139. Name string `json:"name" validate:"required"`
  6140. }
  6141. var input struct {
  6142. Children map[int]child `json:"children" validate:"required,gt=0,dive"`
  6143. }
  6144. input.Children = map[int]child{
  6145. 0: {Name: "ok"},
  6146. 1: {Name: ""},
  6147. }
  6148. errs := validate.Struct(input)
  6149. NotEqual(t, errs, nil)
  6150. ve := errs.(ValidationErrors)
  6151. Equal(t, len(ve), 1)
  6152. AssertError(t, errs, "children[1].name", "Children[1].Name", "name", "Name", "required")
  6153. }
  6154. func TestFieldLevelName(t *testing.T) {
  6155. type Test struct {
  6156. String string `validate:"custom1" json:"json1"`
  6157. Array []string `validate:"dive,custom2" json:"json2"`
  6158. Map map[string]string `validate:"dive,custom3" json:"json3"`
  6159. Array2 []string `validate:"custom4" json:"json4"`
  6160. Map2 map[string]string `validate:"custom5" json:"json5"`
  6161. }
  6162. var res1, res2, res3, res4, res5, alt1, alt2, alt3, alt4, alt5 string
  6163. validate := New()
  6164. validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
  6165. name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
  6166. if name == "-" {
  6167. return ""
  6168. }
  6169. return name
  6170. })
  6171. validate.RegisterValidation("custom1", func(fl FieldLevel) bool {
  6172. res1 = fl.FieldName()
  6173. alt1 = fl.StructFieldName()
  6174. return true
  6175. })
  6176. validate.RegisterValidation("custom2", func(fl FieldLevel) bool {
  6177. res2 = fl.FieldName()
  6178. alt2 = fl.StructFieldName()
  6179. return true
  6180. })
  6181. validate.RegisterValidation("custom3", func(fl FieldLevel) bool {
  6182. res3 = fl.FieldName()
  6183. alt3 = fl.StructFieldName()
  6184. return true
  6185. })
  6186. validate.RegisterValidation("custom4", func(fl FieldLevel) bool {
  6187. res4 = fl.FieldName()
  6188. alt4 = fl.StructFieldName()
  6189. return true
  6190. })
  6191. validate.RegisterValidation("custom5", func(fl FieldLevel) bool {
  6192. res5 = fl.FieldName()
  6193. alt5 = fl.StructFieldName()
  6194. return true
  6195. })
  6196. test := Test{
  6197. String: "test",
  6198. Array: []string{"1"},
  6199. Map: map[string]string{"test": "test"},
  6200. }
  6201. errs := validate.Struct(test)
  6202. Equal(t, errs, nil)
  6203. Equal(t, res1, "json1")
  6204. Equal(t, alt1, "String")
  6205. Equal(t, res2, "json2[0]")
  6206. Equal(t, alt2, "Array[0]")
  6207. Equal(t, res3, "json3[test]")
  6208. Equal(t, alt3, "Map[test]")
  6209. Equal(t, res4, "json4")
  6210. Equal(t, alt4, "Array2")
  6211. Equal(t, res5, "json5")
  6212. Equal(t, alt5, "Map2")
  6213. }
  6214. func TestValidateStructRegisterCtx(t *testing.T) {
  6215. var ctxVal string
  6216. fnCtx := func(ctx context.Context, fl FieldLevel) bool {
  6217. ctxVal = ctx.Value(&ctxVal).(string)
  6218. return true
  6219. }
  6220. var ctxSlVal string
  6221. slFn := func(ctx context.Context, sl StructLevel) {
  6222. ctxSlVal = ctx.Value(&ctxSlVal).(string)
  6223. }
  6224. type Test struct {
  6225. Field string `validate:"val"`
  6226. }
  6227. var tst Test
  6228. validate := New()
  6229. validate.RegisterValidationCtx("val", fnCtx)
  6230. validate.RegisterStructValidationCtx(slFn, Test{})
  6231. ctx := context.WithValue(context.Background(), &ctxVal, "testval")
  6232. ctx = context.WithValue(ctx, &ctxSlVal, "slVal")
  6233. errs := validate.StructCtx(ctx, tst)
  6234. Equal(t, errs, nil)
  6235. Equal(t, ctxVal, "testval")
  6236. Equal(t, ctxSlVal, "slVal")
  6237. }
  6238. func TestHostnameRFC952Validation(t *testing.T) {
  6239. tests := []struct {
  6240. param string
  6241. expected bool
  6242. }{
  6243. {"test.example.com", true},
  6244. {"example.com", true},
  6245. {"example24.com", true},
  6246. {"test.example24.com", true},
  6247. {"test24.example24.com", true},
  6248. {"example", true},
  6249. {"EXAMPLE", true},
  6250. {"1.foo.com", false},
  6251. {"test.example.com.", false},
  6252. {"example.com.", false},
  6253. {"example24.com.", false},
  6254. {"test.example24.com.", false},
  6255. {"test24.example24.com.", false},
  6256. {"example.", false},
  6257. {"192.168.0.1", false},
  6258. {"email@example.com", false},
  6259. {"2001:cdba:0000:0000:0000:0000:3257:9652", false},
  6260. {"2001:cdba:0:0:0:0:3257:9652", false},
  6261. {"2001:cdba::3257:9652", false},
  6262. }
  6263. validate := New()
  6264. for i, test := range tests {
  6265. errs := validate.Var(test.param, "hostname")
  6266. if test.expected {
  6267. if !IsEqual(errs, nil) {
  6268. t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
  6269. }
  6270. } else {
  6271. if IsEqual(errs, nil) {
  6272. t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
  6273. } else {
  6274. val := getError(errs, "", "")
  6275. if val.Tag() != "hostname" {
  6276. t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
  6277. }
  6278. }
  6279. }
  6280. }
  6281. }
  6282. func TestHostnameRFC1123Validation(t *testing.T) {
  6283. tests := []struct {
  6284. param string
  6285. expected bool
  6286. }{
  6287. {"test.example.com", true},
  6288. {"example.com", true},
  6289. {"example24.com", true},
  6290. {"test.example24.com", true},
  6291. {"test24.example24.com", true},
  6292. {"example", true},
  6293. {"1.foo.com", true},
  6294. {"test.example.com.", false},
  6295. {"example.com.", false},
  6296. {"example24.com.", false},
  6297. {"test.example24.com.", false},
  6298. {"test24.example24.com.", false},
  6299. {"example.", false},
  6300. {"192.168.0.1", true},
  6301. {"email@example.com", false},
  6302. {"2001:cdba:0000:0000:0000:0000:3257:9652", false},
  6303. {"2001:cdba:0:0:0:0:3257:9652", false},
  6304. {"2001:cdba::3257:9652", false},
  6305. }
  6306. validate := New()
  6307. for i, test := range tests {
  6308. errs := validate.Var(test.param, "hostname_rfc1123")
  6309. if test.expected {
  6310. if !IsEqual(errs, nil) {
  6311. t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
  6312. }
  6313. } else {
  6314. if IsEqual(errs, nil) {
  6315. t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
  6316. } else {
  6317. val := getError(errs, "", "")
  6318. if val.Tag() != "hostname_rfc1123" {
  6319. t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
  6320. }
  6321. }
  6322. }
  6323. }
  6324. }
  6325. func TestHostnameRFC1123AliasValidation(t *testing.T) {
  6326. tests := []struct {
  6327. param string
  6328. expected bool
  6329. }{
  6330. {"test.example.com", true},
  6331. {"example.com", true},
  6332. {"example24.com", true},
  6333. {"test.example24.com", true},
  6334. {"test24.example24.com", true},
  6335. {"example", true},
  6336. {"1.foo.com", true},
  6337. {"test.example.com.", false},
  6338. {"example.com.", false},
  6339. {"example24.com.", false},
  6340. {"test.example24.com.", false},
  6341. {"test24.example24.com.", false},
  6342. {"example.", false},
  6343. {"192.168.0.1", true},
  6344. {"email@example.com", false},
  6345. {"2001:cdba:0000:0000:0000:0000:3257:9652", false},
  6346. {"2001:cdba:0:0:0:0:3257:9652", false},
  6347. {"2001:cdba::3257:9652", false},
  6348. }
  6349. validate := New()
  6350. validate.RegisterAlias("hostname", "hostname_rfc1123")
  6351. for i, test := range tests {
  6352. errs := validate.Var(test.param, "hostname")
  6353. if test.expected {
  6354. if !IsEqual(errs, nil) {
  6355. t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
  6356. }
  6357. } else {
  6358. if IsEqual(errs, nil) {
  6359. t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
  6360. } else {
  6361. val := getError(errs, "", "")
  6362. if val.Tag() != "hostname" {
  6363. t.Fatalf("Index: %d hostname failed Error: %v", i, errs)
  6364. }
  6365. }
  6366. }
  6367. }
  6368. }
  6369. func TestFQDNValidation(t *testing.T) {
  6370. tests := []struct {
  6371. param string
  6372. expected bool
  6373. }{
  6374. {"test.example.com", true},
  6375. {"example.com", true},
  6376. {"example24.com", true},
  6377. {"test.example24.com", true},
  6378. {"test24.example24.com", true},
  6379. {"test.example.com.", true},
  6380. {"example.com.", true},
  6381. {"example24.com.", true},
  6382. {"test.example24.com.", true},
  6383. {"test24.example24.com.", true},
  6384. {"test24.example24.com..", false},
  6385. {"example", false},
  6386. {"192.168.0.1", false},
  6387. {"email@example.com", false},
  6388. {"2001:cdba:0000:0000:0000:0000:3257:9652", false},
  6389. {"2001:cdba:0:0:0:0:3257:9652", false},
  6390. {"2001:cdba::3257:9652", false},
  6391. {"", false},
  6392. }
  6393. validate := New()
  6394. for i, test := range tests {
  6395. errs := validate.Var(test.param, "fqdn")
  6396. if test.expected {
  6397. if !IsEqual(errs, nil) {
  6398. t.Fatalf("Index: %d fqdn failed Error: %v", i, errs)
  6399. }
  6400. } else {
  6401. if IsEqual(errs, nil) {
  6402. t.Fatalf("Index: %d fqdn failed Error: %v", i, errs)
  6403. } else {
  6404. val := getError(errs, "", "")
  6405. if val.Tag() != "fqdn" {
  6406. t.Fatalf("Index: %d fqdn failed Error: %v", i, errs)
  6407. }
  6408. }
  6409. }
  6410. }
  6411. }
  6412. func TestIsDefault(t *testing.T) {
  6413. validate := New()
  6414. type Inner struct {
  6415. String string `validate:"isdefault"`
  6416. }
  6417. type Test struct {
  6418. String string `validate:"isdefault"`
  6419. Inner *Inner `validate:"isdefault"`
  6420. }
  6421. var tt Test
  6422. errs := validate.Struct(tt)
  6423. Equal(t, errs, nil)
  6424. tt.Inner = &Inner{String: ""}
  6425. errs = validate.Struct(tt)
  6426. NotEqual(t, errs, nil)
  6427. fe := errs.(ValidationErrors)[0]
  6428. Equal(t, fe.Field(), "Inner")
  6429. Equal(t, fe.Namespace(), "Test.Inner")
  6430. Equal(t, fe.Tag(), "isdefault")
  6431. validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
  6432. name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
  6433. if name == "-" {
  6434. return ""
  6435. }
  6436. return name
  6437. })
  6438. type Inner2 struct {
  6439. String string `validate:"isdefault"`
  6440. }
  6441. type Test2 struct {
  6442. Inner Inner2 `validate:"isdefault" json:"inner"`
  6443. }
  6444. var t2 Test2
  6445. errs = validate.Struct(t2)
  6446. Equal(t, errs, nil)
  6447. t2.Inner.String = "Changed"
  6448. errs = validate.Struct(t2)
  6449. NotEqual(t, errs, nil)
  6450. fe = errs.(ValidationErrors)[0]
  6451. Equal(t, fe.Field(), "inner")
  6452. Equal(t, fe.Namespace(), "Test2.inner")
  6453. Equal(t, fe.Tag(), "isdefault")
  6454. }
  6455. func TestUniqueValidation(t *testing.T) {
  6456. tests := []struct {
  6457. param interface{}
  6458. expected bool
  6459. }{
  6460. // Arrays
  6461. {[2]string{"a", "b"}, true},
  6462. {[2]int{1, 2}, true},
  6463. {[2]float64{1, 2}, true},
  6464. {[2]interface{}{"a", "b"}, true},
  6465. {[2]interface{}{"a", 1}, true},
  6466. {[2]float64{1, 1}, false},
  6467. {[2]int{1, 1}, false},
  6468. {[2]string{"a", "a"}, false},
  6469. {[2]interface{}{"a", "a"}, false},
  6470. {[4]interface{}{"a", 1, "b", 1}, false},
  6471. // Slices
  6472. {[]string{"a", "b"}, true},
  6473. {[]int{1, 2}, true},
  6474. {[]float64{1, 2}, true},
  6475. {[]interface{}{"a", "b"}, true},
  6476. {[]interface{}{"a", 1}, true},
  6477. {[]float64{1, 1}, false},
  6478. {[]int{1, 1}, false},
  6479. {[]string{"a", "a"}, false},
  6480. {[]interface{}{"a", "a"}, false},
  6481. {[]interface{}{"a", 1, "b", 1}, false},
  6482. // Maps
  6483. {map[string]string{"one": "a", "two": "b"}, true},
  6484. {map[string]int{"one": 1, "two": 2}, true},
  6485. {map[string]float64{"one": 1, "two": 2}, true},
  6486. {map[string]interface{}{"one": "a", "two": "b"}, true},
  6487. {map[string]interface{}{"one": "a", "two": 1}, true},
  6488. {map[string]float64{"one": 1, "two": 1}, false},
  6489. {map[string]int{"one": 1, "two": 1}, false},
  6490. {map[string]string{"one": "a", "two": "a"}, false},
  6491. {map[string]interface{}{"one": "a", "two": "a"}, false},
  6492. {map[string]interface{}{"one": "a", "two": 1, "three": "b", "four": 1}, false},
  6493. }
  6494. validate := New()
  6495. for i, test := range tests {
  6496. errs := validate.Var(test.param, "unique")
  6497. if test.expected {
  6498. if !IsEqual(errs, nil) {
  6499. t.Fatalf("Index: %d unique failed Error: %v", i, errs)
  6500. }
  6501. } else {
  6502. if IsEqual(errs, nil) {
  6503. t.Fatalf("Index: %d unique failed Error: %v", i, errs)
  6504. } else {
  6505. val := getError(errs, "", "")
  6506. if val.Tag() != "unique" {
  6507. t.Fatalf("Index: %d unique failed Error: %v", i, errs)
  6508. }
  6509. }
  6510. }
  6511. }
  6512. PanicMatches(t, func() { validate.Var(1.0, "unique") }, "Bad field type float64")
  6513. }
  6514. func TestHTMLValidation(t *testing.T) {
  6515. tests := []struct {
  6516. param string
  6517. expected bool
  6518. }{
  6519. {"<html>", true},
  6520. {"<script>", true},
  6521. {"<stillworks>", true},
  6522. {"</html", false},
  6523. {"</script>", true},
  6524. {"<//script>", false},
  6525. {"<123nonsense>", false},
  6526. {"test", false},
  6527. {"&example", false},
  6528. }
  6529. validate := New()
  6530. for i, test := range tests {
  6531. errs := validate.Var(test.param, "html")
  6532. if test.expected {
  6533. if !IsEqual(errs, nil) {
  6534. t.Fatalf("Index: %d html failed Error: %v", i, errs)
  6535. }
  6536. } else {
  6537. if IsEqual(errs, nil) {
  6538. t.Fatalf("Index: %d html failed Error: %v", i, errs)
  6539. } else {
  6540. val := getError(errs, "", "")
  6541. if val.Tag() != "html" {
  6542. t.Fatalf("Index: %d html failed Error: %v", i, errs)
  6543. }
  6544. }
  6545. }
  6546. }
  6547. }
  6548. func TestHTMLEncodedValidation(t *testing.T) {
  6549. tests := []struct {
  6550. param string
  6551. expected bool
  6552. }{
  6553. {"&#x3c;", true},
  6554. {"&#xaf;", true},
  6555. {"&#x00;", true},
  6556. {"&#xf0;", true},
  6557. {"&#x3c", true},
  6558. {"&#xaf", true},
  6559. {"&#x00", true},
  6560. {"&#xf0", true},
  6561. {"&#ab", true},
  6562. {"&lt;", true},
  6563. {"&gt;", true},
  6564. {"&quot;", true},
  6565. {"&amp;", true},
  6566. {"#x0a", false},
  6567. {"&x00", false},
  6568. {"&#x1z", false},
  6569. }
  6570. validate := New()
  6571. for i, test := range tests {
  6572. errs := validate.Var(test.param, "html_encoded")
  6573. if test.expected {
  6574. if !IsEqual(errs, nil) {
  6575. t.Fatalf("Index: %d html_encoded failed Error: %v", i, errs)
  6576. }
  6577. } else {
  6578. if IsEqual(errs, nil) {
  6579. t.Fatalf("Index: %d html_enocded failed Error: %v", i, errs)
  6580. } else {
  6581. val := getError(errs, "", "")
  6582. if val.Tag() != "html_encoded" {
  6583. t.Fatalf("Index: %d html_encoded failed Error: %v", i, errs)
  6584. }
  6585. }
  6586. }
  6587. }
  6588. }
  6589. func TestURLEncodedValidation(t *testing.T) {
  6590. tests := []struct {
  6591. param string
  6592. expected bool
  6593. }{
  6594. {"%20", true},
  6595. {"%af", true},
  6596. {"%ff", true},
  6597. {"<%az", false},
  6598. {"%test%", false},
  6599. {"a%b", false},
  6600. {"1%2", false},
  6601. {"%%a%%", false},
  6602. }
  6603. validate := New()
  6604. for i, test := range tests {
  6605. errs := validate.Var(test.param, "url_encoded")
  6606. if test.expected {
  6607. if !IsEqual(errs, nil) {
  6608. t.Fatalf("Index: %d url_encoded failed Error: %v", i, errs)
  6609. }
  6610. } else {
  6611. if IsEqual(errs, nil) {
  6612. t.Fatalf("Index: %d url_enocded failed Error: %v", i, errs)
  6613. } else {
  6614. val := getError(errs, "", "")
  6615. if val.Tag() != "url_encoded" {
  6616. t.Fatalf("Index: %d url_encoded failed Error: %v", i, errs)
  6617. }
  6618. }
  6619. }
  6620. }
  6621. }
  6622. func TestKeys(t *testing.T) {
  6623. type Test struct {
  6624. Test1 map[string]string `validate:"gt=0,dive,keys,eq=testkey,endkeys,eq=testval" json:"test1"`
  6625. Test2 map[int]int `validate:"gt=0,dive,keys,eq=3,endkeys,eq=4" json:"test2"`
  6626. Test3 map[int]int `validate:"gt=0,dive,keys,eq=3,endkeys" json:"test3"`
  6627. }
  6628. var tst Test
  6629. validate := New()
  6630. err := validate.Struct(tst)
  6631. NotEqual(t, err, nil)
  6632. Equal(t, len(err.(ValidationErrors)), 3)
  6633. AssertError(t, err.(ValidationErrors), "Test.Test1", "Test.Test1", "Test1", "Test1", "gt")
  6634. AssertError(t, err.(ValidationErrors), "Test.Test2", "Test.Test2", "Test2", "Test2", "gt")
  6635. AssertError(t, err.(ValidationErrors), "Test.Test3", "Test.Test3", "Test3", "Test3", "gt")
  6636. tst.Test1 = map[string]string{
  6637. "testkey": "testval",
  6638. }
  6639. tst.Test2 = map[int]int{
  6640. 3: 4,
  6641. }
  6642. tst.Test3 = map[int]int{
  6643. 3: 4,
  6644. }
  6645. err = validate.Struct(tst)
  6646. Equal(t, err, nil)
  6647. tst.Test1["badtestkey"] = "badtestvalue"
  6648. tst.Test2[10] = 11
  6649. err = validate.Struct(tst)
  6650. NotEqual(t, err, nil)
  6651. errs := err.(ValidationErrors)
  6652. Equal(t, len(errs), 4)
  6653. AssertDeepError(t, errs, "Test.Test1[badtestkey]", "Test.Test1[badtestkey]", "Test1[badtestkey]", "Test1[badtestkey]", "eq", "eq")
  6654. AssertDeepError(t, errs, "Test.Test1[badtestkey]", "Test.Test1[badtestkey]", "Test1[badtestkey]", "Test1[badtestkey]", "eq", "eq")
  6655. AssertDeepError(t, errs, "Test.Test2[10]", "Test.Test2[10]", "Test2[10]", "Test2[10]", "eq", "eq")
  6656. AssertDeepError(t, errs, "Test.Test2[10]", "Test.Test2[10]", "Test2[10]", "Test2[10]", "eq", "eq")
  6657. type Test2 struct {
  6658. NestedKeys map[[1]string]string `validate:"gt=0,dive,keys,dive,eq=innertestkey,endkeys,eq=outertestval"`
  6659. }
  6660. var tst2 Test2
  6661. err = validate.Struct(tst2)
  6662. NotEqual(t, err, nil)
  6663. Equal(t, len(err.(ValidationErrors)), 1)
  6664. AssertError(t, err.(ValidationErrors), "Test2.NestedKeys", "Test2.NestedKeys", "NestedKeys", "NestedKeys", "gt")
  6665. tst2.NestedKeys = map[[1]string]string{
  6666. [1]string{"innertestkey"}: "outertestval",
  6667. }
  6668. err = validate.Struct(tst2)
  6669. Equal(t, err, nil)
  6670. tst2.NestedKeys[[1]string{"badtestkey"}] = "badtestvalue"
  6671. err = validate.Struct(tst2)
  6672. NotEqual(t, err, nil)
  6673. errs = err.(ValidationErrors)
  6674. Equal(t, len(errs), 2)
  6675. AssertDeepError(t, errs, "Test2.NestedKeys[[badtestkey]][0]", "Test2.NestedKeys[[badtestkey]][0]", "NestedKeys[[badtestkey]][0]", "NestedKeys[[badtestkey]][0]", "eq", "eq")
  6676. AssertDeepError(t, errs, "Test2.NestedKeys[[badtestkey]]", "Test2.NestedKeys[[badtestkey]]", "NestedKeys[[badtestkey]]", "NestedKeys[[badtestkey]]", "eq", "eq")
  6677. // test bad tag definitions
  6678. PanicMatches(t, func() { validate.Var(map[string]string{"key": "val"}, "endkeys,dive,eq=val") }, "'endkeys' tag encountered without a corresponding 'keys' tag")
  6679. PanicMatches(t, func() { validate.Var(1, "keys,eq=1,endkeys") }, "'keys' tag must be immediately preceded by the 'dive' tag")
  6680. // test custom tag name
  6681. validate = New()
  6682. validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
  6683. name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
  6684. if name == "-" {
  6685. return ""
  6686. }
  6687. return name
  6688. })
  6689. err = validate.Struct(tst)
  6690. NotEqual(t, err, nil)
  6691. errs = err.(ValidationErrors)
  6692. Equal(t, len(errs), 4)
  6693. AssertDeepError(t, errs, "Test.test1[badtestkey]", "Test.Test1[badtestkey]", "test1[badtestkey]", "Test1[badtestkey]", "eq", "eq")
  6694. AssertDeepError(t, errs, "Test.test1[badtestkey]", "Test.Test1[badtestkey]", "test1[badtestkey]", "Test1[badtestkey]", "eq", "eq")
  6695. AssertDeepError(t, errs, "Test.test2[10]", "Test.Test2[10]", "test2[10]", "Test2[10]", "eq", "eq")
  6696. AssertDeepError(t, errs, "Test.test2[10]", "Test.Test2[10]", "test2[10]", "Test2[10]", "eq", "eq")
  6697. }
  6698. // Thanks @adrian-sgn specific test for your specific scenario
  6699. func TestKeysCustomValidation(t *testing.T) {
  6700. type LangCode string
  6701. type Label map[LangCode]string
  6702. type TestMapStructPtr struct {
  6703. Label Label `validate:"dive,keys,lang_code,endkeys,required"`
  6704. }
  6705. validate := New()
  6706. validate.RegisterValidation("lang_code", func(fl FieldLevel) bool {
  6707. validLangCodes := map[LangCode]struct{}{
  6708. "en": {},
  6709. "es": {},
  6710. "pt": {},
  6711. }
  6712. _, ok := validLangCodes[fl.Field().Interface().(LangCode)]
  6713. return ok
  6714. })
  6715. label := Label{
  6716. "en": "Good morning!",
  6717. "pt": "",
  6718. "es": "¡Buenos días!",
  6719. "xx": "Bad key",
  6720. "xxx": "",
  6721. }
  6722. err := validate.Struct(TestMapStructPtr{label})
  6723. NotEqual(t, err, nil)
  6724. errs := err.(ValidationErrors)
  6725. Equal(t, len(errs), 4)
  6726. AssertDeepError(t, errs, "TestMapStructPtr.Label[xx]", "TestMapStructPtr.Label[xx]", "Label[xx]", "Label[xx]", "lang_code", "lang_code")
  6727. AssertDeepError(t, errs, "TestMapStructPtr.Label[pt]", "TestMapStructPtr.Label[pt]", "Label[pt]", "Label[pt]", "required", "required")
  6728. AssertDeepError(t, errs, "TestMapStructPtr.Label[xxx]", "TestMapStructPtr.Label[xxx]", "Label[xxx]", "Label[xxx]", "lang_code", "lang_code")
  6729. AssertDeepError(t, errs, "TestMapStructPtr.Label[xxx]", "TestMapStructPtr.Label[xxx]", "Label[xxx]", "Label[xxx]", "required", "required")
  6730. // find specific error
  6731. var e FieldError
  6732. for _, e = range errs {
  6733. if e.Namespace() == "TestMapStructPtr.Label[xxx]" {
  6734. break
  6735. }
  6736. }
  6737. Equal(t, e.Param(), "")
  6738. Equal(t, e.Value().(LangCode), LangCode("xxx"))
  6739. for _, e = range errs {
  6740. if e.Namespace() == "TestMapStructPtr.Label[xxx]" && e.Tag() == "required" {
  6741. break
  6742. }
  6743. }
  6744. Equal(t, e.Param(), "")
  6745. Equal(t, e.Value().(string), "")
  6746. }
  6747. func TestKeyOrs(t *testing.T) {
  6748. type Test struct {
  6749. Test1 map[string]string `validate:"gt=0,dive,keys,eq=testkey|eq=testkeyok,endkeys,eq=testval" json:"test1"`
  6750. }
  6751. var tst Test
  6752. validate := New()
  6753. err := validate.Struct(tst)
  6754. NotEqual(t, err, nil)
  6755. Equal(t, len(err.(ValidationErrors)), 1)
  6756. AssertError(t, err.(ValidationErrors), "Test.Test1", "Test.Test1", "Test1", "Test1", "gt")
  6757. tst.Test1 = map[string]string{
  6758. "testkey": "testval",
  6759. }
  6760. err = validate.Struct(tst)
  6761. Equal(t, err, nil)
  6762. tst.Test1["badtestkey"] = "badtestval"
  6763. err = validate.Struct(tst)
  6764. NotEqual(t, err, nil)
  6765. errs := err.(ValidationErrors)
  6766. Equal(t, len(errs), 2)
  6767. AssertDeepError(t, errs, "Test.Test1[badtestkey]", "Test.Test1[badtestkey]", "Test1[badtestkey]", "Test1[badtestkey]", "eq=testkey|eq=testkeyok", "eq=testkey|eq=testkeyok")
  6768. AssertDeepError(t, errs, "Test.Test1[badtestkey]", "Test.Test1[badtestkey]", "Test1[badtestkey]", "Test1[badtestkey]", "eq", "eq")
  6769. validate.RegisterAlias("okkey", "eq=testkey|eq=testkeyok")
  6770. type Test2 struct {
  6771. Test1 map[string]string `validate:"gt=0,dive,keys,okkey,endkeys,eq=testval" json:"test1"`
  6772. }
  6773. var tst2 Test2
  6774. err = validate.Struct(tst2)
  6775. NotEqual(t, err, nil)
  6776. Equal(t, len(err.(ValidationErrors)), 1)
  6777. AssertError(t, err.(ValidationErrors), "Test2.Test1", "Test2.Test1", "Test1", "Test1", "gt")
  6778. tst2.Test1 = map[string]string{
  6779. "testkey": "testval",
  6780. }
  6781. err = validate.Struct(tst2)
  6782. Equal(t, err, nil)
  6783. tst2.Test1["badtestkey"] = "badtestval"
  6784. err = validate.Struct(tst2)
  6785. NotEqual(t, err, nil)
  6786. errs = err.(ValidationErrors)
  6787. Equal(t, len(errs), 2)
  6788. AssertDeepError(t, errs, "Test2.Test1[badtestkey]", "Test2.Test1[badtestkey]", "Test1[badtestkey]", "Test1[badtestkey]", "okkey", "eq=testkey|eq=testkeyok")
  6789. AssertDeepError(t, errs, "Test2.Test1[badtestkey]", "Test2.Test1[badtestkey]", "Test1[badtestkey]", "Test1[badtestkey]", "eq", "eq")
  6790. }
  6791. func TestStructLevelValidationsPointerPassing(t *testing.T) {
  6792. v1 := New()
  6793. v1.RegisterStructValidation(StructValidationTestStruct, &TestStruct{})
  6794. tst := &TestStruct{
  6795. String: "good value",
  6796. }
  6797. errs := v1.Struct(tst)
  6798. NotEqual(t, errs, nil)
  6799. AssertError(t, errs, "TestStruct.StringVal", "TestStruct.String", "StringVal", "String", "badvalueteststruct")
  6800. }
  6801. func TestDirValidation(t *testing.T) {
  6802. validate := New()
  6803. tests := []struct {
  6804. title string
  6805. param string
  6806. expected bool
  6807. }{
  6808. {"existing dir", "testdata", true},
  6809. {"existing self dir", ".", true},
  6810. {"existing parent dir", "..", true},
  6811. {"empty dir", "", false},
  6812. {"missing dir", "non_existing_testdata", false},
  6813. {"a file not a directory", filepath.Join("testdata", "a.go"), false},
  6814. }
  6815. for _, test := range tests {
  6816. errs := validate.Var(test.param, "dir")
  6817. if test.expected {
  6818. if !IsEqual(errs, nil) {
  6819. t.Fatalf("Test: '%s' failed Error: %s", test.title, errs)
  6820. }
  6821. } else {
  6822. if IsEqual(errs, nil) {
  6823. t.Fatalf("Test: '%s' failed Error: %s", test.title, errs)
  6824. }
  6825. }
  6826. }
  6827. PanicMatches(t, func() {
  6828. validate.Var(2, "dir")
  6829. }, "Bad field type int")
  6830. }
  6831. func TestStartsWithValidation(t *testing.T) {
  6832. tests := []struct {
  6833. Value string `validate:"startswith=(/^ヮ^)/*:・゚✧"`
  6834. Tag string
  6835. ExpectedNil bool
  6836. }{
  6837. {Value: "(/^ヮ^)/*:・゚✧ glitter", Tag: "startswith=(/^ヮ^)/*:・゚✧", ExpectedNil: true},
  6838. {Value: "abcd", Tag: "startswith=(/^ヮ^)/*:・゚✧", ExpectedNil: false},
  6839. }
  6840. validate := New()
  6841. for i, s := range tests {
  6842. errs := validate.Var(s.Value, s.Tag)
  6843. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  6844. t.Fatalf("Index: %d failed Error: %s", i, errs)
  6845. }
  6846. errs = validate.Struct(s)
  6847. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  6848. t.Fatalf("Index: %d failed Error: %s", i, errs)
  6849. }
  6850. }
  6851. }
  6852. func TestEndsWithValidation(t *testing.T) {
  6853. tests := []struct {
  6854. Value string `validate:"endswith=(/^ヮ^)/*:・゚✧"`
  6855. Tag string
  6856. ExpectedNil bool
  6857. }{
  6858. {Value: "glitter (/^ヮ^)/*:・゚✧", Tag: "endswith=(/^ヮ^)/*:・゚✧", ExpectedNil: true},
  6859. {Value: "(/^ヮ^)/*:・゚✧ glitter", Tag: "endswith=(/^ヮ^)/*:・゚✧", ExpectedNil: false},
  6860. }
  6861. validate := New()
  6862. for i, s := range tests {
  6863. errs := validate.Var(s.Value, s.Tag)
  6864. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  6865. t.Fatalf("Index: %d failed Error: %s", i, errs)
  6866. }
  6867. errs = validate.Struct(s)
  6868. if (s.ExpectedNil && errs != nil) || (!s.ExpectedNil && errs == nil) {
  6869. t.Fatalf("Index: %d failed Error: %s", i, errs)
  6870. }
  6871. }
  6872. }
  6873. func TestRequiredWith(t *testing.T) {
  6874. fieldVal := "test"
  6875. test := struct {
  6876. FieldE string `validate:"omitempty" json:"field_e"`
  6877. FieldER string `validate:"required_with=FieldE" json:"field_er"`
  6878. Field1 string `validate:"omitempty" json:"field_1"`
  6879. Field2 *string `validate:"required_with=Field1" json:"field_2"`
  6880. Field3 map[string]string `validate:"required_with=Field2" json:"field_3"`
  6881. Field4 interface{} `validate:"required_with=Field3" json:"field_4"`
  6882. Field5 string `validate:"required_with=Field3" json:"field_5"`
  6883. }{
  6884. Field1: "test_field1",
  6885. Field2: &fieldVal,
  6886. Field3: map[string]string{"key": "val"},
  6887. Field4: "test",
  6888. Field5: "test",
  6889. }
  6890. validate := New()
  6891. errs := validate.Struct(test)
  6892. if errs != nil {
  6893. t.Fatalf("failed Error: %s", errs)
  6894. }
  6895. }
  6896. func TestRequiredWithAll(t *testing.T) {
  6897. fieldVal := "test"
  6898. test := struct {
  6899. FieldE string `validate:"omitempty" json:"field_e"`
  6900. FieldER string `validate:"required_with_all=FieldE" json:"field_er"`
  6901. Field1 string `validate:"omitempty" json:"field_1"`
  6902. Field2 *string `validate:"required_with_all=Field1" json:"field_2"`
  6903. Field3 map[string]string `validate:"required_with_all=Field2" json:"field_3"`
  6904. Field4 interface{} `validate:"required_with_all=Field3" json:"field_4"`
  6905. Field5 string `validate:"required_with_all=Field3" json:"field_5"`
  6906. }{
  6907. Field1: "test_field1",
  6908. Field2: &fieldVal,
  6909. Field3: map[string]string{"key": "val"},
  6910. Field4: "test",
  6911. Field5: "test",
  6912. }
  6913. validate := New()
  6914. errs := validate.Struct(test)
  6915. if errs != nil {
  6916. t.Fatalf("failed Error: %s", errs)
  6917. }
  6918. }
  6919. func TestRequiredWithout(t *testing.T) {
  6920. fieldVal := "test"
  6921. test := struct {
  6922. Field1 string `validate:"omitempty" json:"field_1"`
  6923. Field2 *string `validate:"required_without=Field1" json:"field_2"`
  6924. Field3 map[string]string `validate:"required_without=Field2" json:"field_3"`
  6925. Field4 interface{} `validate:"required_without=Field3" json:"field_4"`
  6926. Field5 string `validate:"required_without=Field3" json:"field_5"`
  6927. }{
  6928. Field2: &fieldVal,
  6929. Field3: map[string]string{"key": "val"},
  6930. Field4: "test",
  6931. Field5: "test",
  6932. }
  6933. validate := New()
  6934. errs := validate.Struct(test)
  6935. if errs != nil {
  6936. t.Fatalf("failed Error: %s", errs)
  6937. }
  6938. test2 := struct {
  6939. Field1 string `validate:"omitempty" json:"field_1"`
  6940. Field2 *string `validate:"required_without=Field1" json:"field_2"`
  6941. Field3 map[string]string `validate:"required_without=Field2" json:"field_3"`
  6942. Field4 interface{} `validate:"required_without=Field3" json:"field_4"`
  6943. Field5 string `validate:"required_without=Field3" json:"field_5"`
  6944. Field6 string `validate:"required_without=Field1" json:"field_6"`
  6945. }{
  6946. Field3: map[string]string{"key": "val"},
  6947. Field4: "test",
  6948. Field5: "test",
  6949. }
  6950. errs = validate.Struct(&test2)
  6951. if errs == nil {
  6952. t.Fatalf("failed Error: %s", errs)
  6953. }
  6954. }
  6955. func TestRequiredWithoutAll(t *testing.T) {
  6956. fieldVal := "test"
  6957. test := struct {
  6958. Field1 string `validate:"omitempty" json:"field_1"`
  6959. Field2 *string `validate:"required_without_all=Field1" json:"field_2"`
  6960. Field3 map[string]string `validate:"required_without_all=Field2" json:"field_3"`
  6961. Field4 interface{} `validate:"required_without_all=Field3" json:"field_4"`
  6962. Field5 string `validate:"required_without_all=Field3" json:"field_5"`
  6963. }{
  6964. Field1: "",
  6965. Field2: &fieldVal,
  6966. Field3: map[string]string{"key": "val"},
  6967. Field4: "test",
  6968. Field5: "test",
  6969. }
  6970. validate := New()
  6971. errs := validate.Struct(test)
  6972. if errs != nil {
  6973. t.Fatalf("failed Error: %s", errs)
  6974. }
  6975. test2 := struct {
  6976. Field1 string `validate:"omitempty" json:"field_1"`
  6977. Field2 *string `validate:"required_without_all=Field1" json:"field_2"`
  6978. Field3 map[string]string `validate:"required_without_all=Field2" json:"field_3"`
  6979. Field4 interface{} `validate:"required_without_all=Field3" json:"field_4"`
  6980. Field5 string `validate:"required_without_all=Field3" json:"field_5"`
  6981. Field6 string `validate:"required_without_all=Field1" json:"field_6"`
  6982. }{
  6983. Field3: map[string]string{"key": "val"},
  6984. Field4: "test",
  6985. Field5: "test",
  6986. }
  6987. errs = validate.Struct(test2)
  6988. if errs == nil {
  6989. t.Fatalf("failed Error: %s", errs)
  6990. }
  6991. }