validation.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. // Copyright 2015 xeipuuv ( https://github.com/xeipuuv )
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // author xeipuuv
  15. // author-github https://github.com/xeipuuv
  16. // author-mail xeipuuv@gmail.com
  17. //
  18. // repository-name gojsonschema
  19. // repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
  20. //
  21. // description Extends Schema and subSchema, implements the validation phase.
  22. //
  23. // created 28-02-2013
  24. package gojsonschema
  25. import (
  26. "encoding/json"
  27. "math/big"
  28. "reflect"
  29. "regexp"
  30. "strconv"
  31. "strings"
  32. "unicode/utf8"
  33. )
  34. // Validate loads and validates a JSON schema
  35. func Validate(ls JSONLoader, ld JSONLoader) (*Result, error) {
  36. // load schema
  37. schema, err := NewSchema(ls)
  38. if err != nil {
  39. return nil, err
  40. }
  41. return schema.Validate(ld)
  42. }
  43. // Validate loads and validates a JSON document
  44. func (v *Schema) Validate(l JSONLoader) (*Result, error) {
  45. root, err := l.LoadJSON()
  46. if err != nil {
  47. return nil, err
  48. }
  49. return v.validateDocument(root), nil
  50. }
  51. func (v *Schema) validateDocument(root interface{}) *Result {
  52. result := &Result{}
  53. context := NewJsonContext(STRING_CONTEXT_ROOT, nil)
  54. v.rootSchema.validateRecursive(v.rootSchema, root, result, context)
  55. return result
  56. }
  57. func (v *subSchema) subValidateWithContext(document interface{}, context *JsonContext) *Result {
  58. result := &Result{}
  59. v.validateRecursive(v, document, result, context)
  60. return result
  61. }
  62. // Walker function to validate the json recursively against the subSchema
  63. func (v *subSchema) validateRecursive(currentSubSchema *subSchema, currentNode interface{}, result *Result, context *JsonContext) {
  64. if internalLogEnabled {
  65. internalLog("validateRecursive %s", context.String())
  66. internalLog(" %v", currentNode)
  67. }
  68. // Handle true/false schema as early as possible as all other fields will be nil
  69. if currentSubSchema.pass != nil {
  70. if !*currentSubSchema.pass {
  71. result.addInternalError(
  72. new(FalseError),
  73. context,
  74. currentNode,
  75. ErrorDetails{},
  76. )
  77. }
  78. return
  79. }
  80. // Handle referenced schemas, returns directly when a $ref is found
  81. if currentSubSchema.refSchema != nil {
  82. v.validateRecursive(currentSubSchema.refSchema, currentNode, result, context)
  83. return
  84. }
  85. // Check for null value
  86. if currentNode == nil {
  87. if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_NULL) {
  88. result.addInternalError(
  89. new(InvalidTypeError),
  90. context,
  91. currentNode,
  92. ErrorDetails{
  93. "expected": currentSubSchema.types.String(),
  94. "given": TYPE_NULL,
  95. },
  96. )
  97. return
  98. }
  99. currentSubSchema.validateSchema(currentSubSchema, currentNode, result, context)
  100. v.validateCommon(currentSubSchema, currentNode, result, context)
  101. } else { // Not a null value
  102. if isJSONNumber(currentNode) {
  103. value := currentNode.(json.Number)
  104. isInt := checkJSONInteger(value)
  105. validType := currentSubSchema.types.Contains(TYPE_NUMBER) || (isInt && currentSubSchema.types.Contains(TYPE_INTEGER))
  106. if currentSubSchema.types.IsTyped() && !validType {
  107. givenType := TYPE_INTEGER
  108. if !isInt {
  109. givenType = TYPE_NUMBER
  110. }
  111. result.addInternalError(
  112. new(InvalidTypeError),
  113. context,
  114. currentNode,
  115. ErrorDetails{
  116. "expected": currentSubSchema.types.String(),
  117. "given": givenType,
  118. },
  119. )
  120. return
  121. }
  122. currentSubSchema.validateSchema(currentSubSchema, value, result, context)
  123. v.validateNumber(currentSubSchema, value, result, context)
  124. v.validateCommon(currentSubSchema, value, result, context)
  125. v.validateString(currentSubSchema, value, result, context)
  126. } else {
  127. rValue := reflect.ValueOf(currentNode)
  128. rKind := rValue.Kind()
  129. switch rKind {
  130. // Slice => JSON array
  131. case reflect.Slice:
  132. if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_ARRAY) {
  133. result.addInternalError(
  134. new(InvalidTypeError),
  135. context,
  136. currentNode,
  137. ErrorDetails{
  138. "expected": currentSubSchema.types.String(),
  139. "given": TYPE_ARRAY,
  140. },
  141. )
  142. return
  143. }
  144. castCurrentNode := currentNode.([]interface{})
  145. currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context)
  146. v.validateArray(currentSubSchema, castCurrentNode, result, context)
  147. v.validateCommon(currentSubSchema, castCurrentNode, result, context)
  148. // Map => JSON object
  149. case reflect.Map:
  150. if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_OBJECT) {
  151. result.addInternalError(
  152. new(InvalidTypeError),
  153. context,
  154. currentNode,
  155. ErrorDetails{
  156. "expected": currentSubSchema.types.String(),
  157. "given": TYPE_OBJECT,
  158. },
  159. )
  160. return
  161. }
  162. castCurrentNode, ok := currentNode.(map[string]interface{})
  163. if !ok {
  164. castCurrentNode = convertDocumentNode(currentNode).(map[string]interface{})
  165. }
  166. currentSubSchema.validateSchema(currentSubSchema, castCurrentNode, result, context)
  167. v.validateObject(currentSubSchema, castCurrentNode, result, context)
  168. v.validateCommon(currentSubSchema, castCurrentNode, result, context)
  169. for _, pSchema := range currentSubSchema.propertiesChildren {
  170. nextNode, ok := castCurrentNode[pSchema.property]
  171. if ok {
  172. subContext := NewJsonContext(pSchema.property, context)
  173. v.validateRecursive(pSchema, nextNode, result, subContext)
  174. }
  175. }
  176. // Simple JSON values : string, number, boolean
  177. case reflect.Bool:
  178. if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_BOOLEAN) {
  179. result.addInternalError(
  180. new(InvalidTypeError),
  181. context,
  182. currentNode,
  183. ErrorDetails{
  184. "expected": currentSubSchema.types.String(),
  185. "given": TYPE_BOOLEAN,
  186. },
  187. )
  188. return
  189. }
  190. value := currentNode.(bool)
  191. currentSubSchema.validateSchema(currentSubSchema, value, result, context)
  192. v.validateNumber(currentSubSchema, value, result, context)
  193. v.validateCommon(currentSubSchema, value, result, context)
  194. v.validateString(currentSubSchema, value, result, context)
  195. case reflect.String:
  196. if currentSubSchema.types.IsTyped() && !currentSubSchema.types.Contains(TYPE_STRING) {
  197. result.addInternalError(
  198. new(InvalidTypeError),
  199. context,
  200. currentNode,
  201. ErrorDetails{
  202. "expected": currentSubSchema.types.String(),
  203. "given": TYPE_STRING,
  204. },
  205. )
  206. return
  207. }
  208. value := currentNode.(string)
  209. currentSubSchema.validateSchema(currentSubSchema, value, result, context)
  210. v.validateNumber(currentSubSchema, value, result, context)
  211. v.validateCommon(currentSubSchema, value, result, context)
  212. v.validateString(currentSubSchema, value, result, context)
  213. }
  214. }
  215. }
  216. result.incrementScore()
  217. }
  218. // Different kinds of validation there, subSchema / common / array / object / string...
  219. func (v *subSchema) validateSchema(currentSubSchema *subSchema, currentNode interface{}, result *Result, context *JsonContext) {
  220. if internalLogEnabled {
  221. internalLog("validateSchema %s", context.String())
  222. internalLog(" %v", currentNode)
  223. }
  224. if len(currentSubSchema.anyOf) > 0 {
  225. validatedAnyOf := false
  226. var bestValidationResult *Result
  227. for _, anyOfSchema := range currentSubSchema.anyOf {
  228. if !validatedAnyOf {
  229. validationResult := anyOfSchema.subValidateWithContext(currentNode, context)
  230. validatedAnyOf = validationResult.Valid()
  231. if !validatedAnyOf && (bestValidationResult == nil || validationResult.score > bestValidationResult.score) {
  232. bestValidationResult = validationResult
  233. }
  234. }
  235. }
  236. if !validatedAnyOf {
  237. result.addInternalError(new(NumberAnyOfError), context, currentNode, ErrorDetails{})
  238. if bestValidationResult != nil {
  239. // add error messages of closest matching subSchema as
  240. // that's probably the one the user was trying to match
  241. result.mergeErrors(bestValidationResult)
  242. }
  243. }
  244. }
  245. if len(currentSubSchema.oneOf) > 0 {
  246. nbValidated := 0
  247. var bestValidationResult *Result
  248. for _, oneOfSchema := range currentSubSchema.oneOf {
  249. validationResult := oneOfSchema.subValidateWithContext(currentNode, context)
  250. if validationResult.Valid() {
  251. nbValidated++
  252. } else if nbValidated == 0 && (bestValidationResult == nil || validationResult.score > bestValidationResult.score) {
  253. bestValidationResult = validationResult
  254. }
  255. }
  256. if nbValidated != 1 {
  257. result.addInternalError(new(NumberOneOfError), context, currentNode, ErrorDetails{})
  258. if nbValidated == 0 {
  259. // add error messages of closest matching subSchema as
  260. // that's probably the one the user was trying to match
  261. result.mergeErrors(bestValidationResult)
  262. }
  263. }
  264. }
  265. if len(currentSubSchema.allOf) > 0 {
  266. nbValidated := 0
  267. for _, allOfSchema := range currentSubSchema.allOf {
  268. validationResult := allOfSchema.subValidateWithContext(currentNode, context)
  269. if validationResult.Valid() {
  270. nbValidated++
  271. }
  272. result.mergeErrors(validationResult)
  273. }
  274. if nbValidated != len(currentSubSchema.allOf) {
  275. result.addInternalError(new(NumberAllOfError), context, currentNode, ErrorDetails{})
  276. }
  277. }
  278. if currentSubSchema.not != nil {
  279. validationResult := currentSubSchema.not.subValidateWithContext(currentNode, context)
  280. if validationResult.Valid() {
  281. result.addInternalError(new(NumberNotError), context, currentNode, ErrorDetails{})
  282. }
  283. }
  284. if currentSubSchema.dependencies != nil && len(currentSubSchema.dependencies) > 0 {
  285. if isKind(currentNode, reflect.Map) {
  286. for elementKey := range currentNode.(map[string]interface{}) {
  287. if dependency, ok := currentSubSchema.dependencies[elementKey]; ok {
  288. switch dependency := dependency.(type) {
  289. case []string:
  290. for _, dependOnKey := range dependency {
  291. if _, dependencyResolved := currentNode.(map[string]interface{})[dependOnKey]; !dependencyResolved {
  292. result.addInternalError(
  293. new(MissingDependencyError),
  294. context,
  295. currentNode,
  296. ErrorDetails{"dependency": dependOnKey},
  297. )
  298. }
  299. }
  300. case *subSchema:
  301. dependency.validateRecursive(dependency, currentNode, result, context)
  302. }
  303. }
  304. }
  305. }
  306. }
  307. if currentSubSchema._if != nil {
  308. validationResultIf := currentSubSchema._if.subValidateWithContext(currentNode, context)
  309. if currentSubSchema._then != nil && validationResultIf.Valid() {
  310. validationResultThen := currentSubSchema._then.subValidateWithContext(currentNode, context)
  311. if !validationResultThen.Valid() {
  312. result.addInternalError(new(ConditionThenError), context, currentNode, ErrorDetails{})
  313. result.mergeErrors(validationResultThen)
  314. }
  315. }
  316. if currentSubSchema._else != nil && !validationResultIf.Valid() {
  317. validationResultElse := currentSubSchema._else.subValidateWithContext(currentNode, context)
  318. if !validationResultElse.Valid() {
  319. result.addInternalError(new(ConditionElseError), context, currentNode, ErrorDetails{})
  320. result.mergeErrors(validationResultElse)
  321. }
  322. }
  323. }
  324. result.incrementScore()
  325. }
  326. func (v *subSchema) validateCommon(currentSubSchema *subSchema, value interface{}, result *Result, context *JsonContext) {
  327. if internalLogEnabled {
  328. internalLog("validateCommon %s", context.String())
  329. internalLog(" %v", value)
  330. }
  331. // const:
  332. if currentSubSchema._const != nil {
  333. vString, err := marshalWithoutNumber(value)
  334. if err != nil {
  335. result.addInternalError(new(InternalError), context, value, ErrorDetails{"error": err})
  336. }
  337. if *vString != *currentSubSchema._const {
  338. result.addInternalError(new(ConstError),
  339. context,
  340. value,
  341. ErrorDetails{
  342. "allowed": *currentSubSchema._const,
  343. },
  344. )
  345. }
  346. }
  347. // enum:
  348. if len(currentSubSchema.enum) > 0 {
  349. vString, err := marshalWithoutNumber(value)
  350. if err != nil {
  351. result.addInternalError(new(InternalError), context, value, ErrorDetails{"error": err})
  352. }
  353. if !isStringInSlice(currentSubSchema.enum, *vString) {
  354. result.addInternalError(
  355. new(EnumError),
  356. context,
  357. value,
  358. ErrorDetails{
  359. "allowed": strings.Join(currentSubSchema.enum, ", "),
  360. },
  361. )
  362. }
  363. }
  364. result.incrementScore()
  365. }
  366. func (v *subSchema) validateArray(currentSubSchema *subSchema, value []interface{}, result *Result, context *JsonContext) {
  367. if internalLogEnabled {
  368. internalLog("validateArray %s", context.String())
  369. internalLog(" %v", value)
  370. }
  371. nbValues := len(value)
  372. // TODO explain
  373. if currentSubSchema.itemsChildrenIsSingleSchema {
  374. for i := range value {
  375. subContext := NewJsonContext(strconv.Itoa(i), context)
  376. validationResult := currentSubSchema.itemsChildren[0].subValidateWithContext(value[i], subContext)
  377. result.mergeErrors(validationResult)
  378. }
  379. } else {
  380. if currentSubSchema.itemsChildren != nil && len(currentSubSchema.itemsChildren) > 0 {
  381. nbItems := len(currentSubSchema.itemsChildren)
  382. // while we have both schemas and values, check them against each other
  383. for i := 0; i != nbItems && i != nbValues; i++ {
  384. subContext := NewJsonContext(strconv.Itoa(i), context)
  385. validationResult := currentSubSchema.itemsChildren[i].subValidateWithContext(value[i], subContext)
  386. result.mergeErrors(validationResult)
  387. }
  388. if nbItems < nbValues {
  389. // we have less schemas than elements in the instance array,
  390. // but that might be ok if "additionalItems" is specified.
  391. switch currentSubSchema.additionalItems.(type) {
  392. case bool:
  393. if !currentSubSchema.additionalItems.(bool) {
  394. result.addInternalError(new(ArrayNoAdditionalItemsError), context, value, ErrorDetails{})
  395. }
  396. case *subSchema:
  397. additionalItemSchema := currentSubSchema.additionalItems.(*subSchema)
  398. for i := nbItems; i != nbValues; i++ {
  399. subContext := NewJsonContext(strconv.Itoa(i), context)
  400. validationResult := additionalItemSchema.subValidateWithContext(value[i], subContext)
  401. result.mergeErrors(validationResult)
  402. }
  403. }
  404. }
  405. }
  406. }
  407. // minItems & maxItems
  408. if currentSubSchema.minItems != nil {
  409. if nbValues < int(*currentSubSchema.minItems) {
  410. result.addInternalError(
  411. new(ArrayMinItemsError),
  412. context,
  413. value,
  414. ErrorDetails{"min": *currentSubSchema.minItems},
  415. )
  416. }
  417. }
  418. if currentSubSchema.maxItems != nil {
  419. if nbValues > int(*currentSubSchema.maxItems) {
  420. result.addInternalError(
  421. new(ArrayMaxItemsError),
  422. context,
  423. value,
  424. ErrorDetails{"max": *currentSubSchema.maxItems},
  425. )
  426. }
  427. }
  428. // uniqueItems:
  429. if currentSubSchema.uniqueItems {
  430. var stringifiedItems = make(map[string]int)
  431. for j, v := range value {
  432. vString, err := marshalWithoutNumber(v)
  433. if err != nil {
  434. result.addInternalError(new(InternalError), context, value, ErrorDetails{"err": err})
  435. }
  436. if i, ok := stringifiedItems[*vString]; ok {
  437. result.addInternalError(
  438. new(ItemsMustBeUniqueError),
  439. context,
  440. value,
  441. ErrorDetails{"type": TYPE_ARRAY, "i": i, "j": j},
  442. )
  443. }
  444. stringifiedItems[*vString] = j
  445. }
  446. }
  447. // contains:
  448. if currentSubSchema.contains != nil {
  449. validatedOne := false
  450. var bestValidationResult *Result
  451. for i, v := range value {
  452. subContext := NewJsonContext(strconv.Itoa(i), context)
  453. validationResult := currentSubSchema.contains.subValidateWithContext(v, subContext)
  454. if validationResult.Valid() {
  455. validatedOne = true
  456. break
  457. } else {
  458. if bestValidationResult == nil || validationResult.score > bestValidationResult.score {
  459. bestValidationResult = validationResult
  460. }
  461. }
  462. }
  463. if !validatedOne {
  464. result.addInternalError(
  465. new(ArrayContainsError),
  466. context,
  467. value,
  468. ErrorDetails{},
  469. )
  470. if bestValidationResult != nil {
  471. result.mergeErrors(bestValidationResult)
  472. }
  473. }
  474. }
  475. result.incrementScore()
  476. }
  477. func (v *subSchema) validateObject(currentSubSchema *subSchema, value map[string]interface{}, result *Result, context *JsonContext) {
  478. if internalLogEnabled {
  479. internalLog("validateObject %s", context.String())
  480. internalLog(" %v", value)
  481. }
  482. // minProperties & maxProperties:
  483. if currentSubSchema.minProperties != nil {
  484. if len(value) < int(*currentSubSchema.minProperties) {
  485. result.addInternalError(
  486. new(ArrayMinPropertiesError),
  487. context,
  488. value,
  489. ErrorDetails{"min": *currentSubSchema.minProperties},
  490. )
  491. }
  492. }
  493. if currentSubSchema.maxProperties != nil {
  494. if len(value) > int(*currentSubSchema.maxProperties) {
  495. result.addInternalError(
  496. new(ArrayMaxPropertiesError),
  497. context,
  498. value,
  499. ErrorDetails{"max": *currentSubSchema.maxProperties},
  500. )
  501. }
  502. }
  503. // required:
  504. for _, requiredProperty := range currentSubSchema.required {
  505. _, ok := value[requiredProperty]
  506. if ok {
  507. result.incrementScore()
  508. } else {
  509. result.addInternalError(
  510. new(RequiredError),
  511. context,
  512. value,
  513. ErrorDetails{"property": requiredProperty},
  514. )
  515. }
  516. }
  517. // additionalProperty & patternProperty:
  518. for pk := range value {
  519. // Check whether this property is described by "properties"
  520. found := false
  521. for _, spValue := range currentSubSchema.propertiesChildren {
  522. if pk == spValue.property {
  523. found = true
  524. }
  525. }
  526. // Check whether this property is described by "patternProperties"
  527. ppMatch := v.validatePatternProperty(currentSubSchema, pk, value[pk], result, context)
  528. // If it is not described by neither "properties" nor "patternProperties" it must pass "additionalProperties"
  529. if !found && !ppMatch {
  530. switch ap := currentSubSchema.additionalProperties.(type) {
  531. case bool:
  532. // Handle the boolean case separately as it's cleaner to return a specific error than failing to pass the false schema
  533. if !ap {
  534. result.addInternalError(
  535. new(AdditionalPropertyNotAllowedError),
  536. context,
  537. value[pk],
  538. ErrorDetails{"property": pk},
  539. )
  540. }
  541. case *subSchema:
  542. validationResult := ap.subValidateWithContext(value[pk], NewJsonContext(pk, context))
  543. result.mergeErrors(validationResult)
  544. }
  545. }
  546. }
  547. // propertyNames:
  548. if currentSubSchema.propertyNames != nil {
  549. for pk := range value {
  550. validationResult := currentSubSchema.propertyNames.subValidateWithContext(pk, context)
  551. if !validationResult.Valid() {
  552. result.addInternalError(new(InvalidPropertyNameError),
  553. context,
  554. value, ErrorDetails{
  555. "property": pk,
  556. })
  557. result.mergeErrors(validationResult)
  558. }
  559. }
  560. }
  561. result.incrementScore()
  562. }
  563. func (v *subSchema) validatePatternProperty(currentSubSchema *subSchema, key string, value interface{}, result *Result, context *JsonContext) bool {
  564. if internalLogEnabled {
  565. internalLog("validatePatternProperty %s", context.String())
  566. internalLog(" %s %v", key, value)
  567. }
  568. validated := false
  569. for pk, pv := range currentSubSchema.patternProperties {
  570. if matches, _ := regexp.MatchString(pk, key); matches {
  571. validated = true
  572. subContext := NewJsonContext(key, context)
  573. validationResult := pv.subValidateWithContext(value, subContext)
  574. result.mergeErrors(validationResult)
  575. }
  576. }
  577. if !validated {
  578. return false
  579. }
  580. result.incrementScore()
  581. return true
  582. }
  583. func (v *subSchema) validateString(currentSubSchema *subSchema, value interface{}, result *Result, context *JsonContext) {
  584. // Ignore JSON numbers
  585. if isJSONNumber(value) {
  586. return
  587. }
  588. // Ignore non strings
  589. if !isKind(value, reflect.String) {
  590. return
  591. }
  592. if internalLogEnabled {
  593. internalLog("validateString %s", context.String())
  594. internalLog(" %v", value)
  595. }
  596. stringValue := value.(string)
  597. // minLength & maxLength:
  598. if currentSubSchema.minLength != nil {
  599. if utf8.RuneCount([]byte(stringValue)) < int(*currentSubSchema.minLength) {
  600. result.addInternalError(
  601. new(StringLengthGTEError),
  602. context,
  603. value,
  604. ErrorDetails{"min": *currentSubSchema.minLength},
  605. )
  606. }
  607. }
  608. if currentSubSchema.maxLength != nil {
  609. if utf8.RuneCount([]byte(stringValue)) > int(*currentSubSchema.maxLength) {
  610. result.addInternalError(
  611. new(StringLengthLTEError),
  612. context,
  613. value,
  614. ErrorDetails{"max": *currentSubSchema.maxLength},
  615. )
  616. }
  617. }
  618. // pattern:
  619. if currentSubSchema.pattern != nil {
  620. if !currentSubSchema.pattern.MatchString(stringValue) {
  621. result.addInternalError(
  622. new(DoesNotMatchPatternError),
  623. context,
  624. value,
  625. ErrorDetails{"pattern": currentSubSchema.pattern},
  626. )
  627. }
  628. }
  629. // format
  630. if currentSubSchema.format != "" {
  631. if !FormatCheckers.IsFormat(currentSubSchema.format, stringValue) {
  632. result.addInternalError(
  633. new(DoesNotMatchFormatError),
  634. context,
  635. value,
  636. ErrorDetails{"format": currentSubSchema.format},
  637. )
  638. }
  639. }
  640. result.incrementScore()
  641. }
  642. func (v *subSchema) validateNumber(currentSubSchema *subSchema, value interface{}, result *Result, context *JsonContext) {
  643. // Ignore non numbers
  644. if !isJSONNumber(value) {
  645. return
  646. }
  647. if internalLogEnabled {
  648. internalLog("validateNumber %s", context.String())
  649. internalLog(" %v", value)
  650. }
  651. number := value.(json.Number)
  652. float64Value, _ := new(big.Rat).SetString(string(number))
  653. // multipleOf:
  654. if currentSubSchema.multipleOf != nil {
  655. if q := new(big.Rat).Quo(float64Value, currentSubSchema.multipleOf); !q.IsInt() {
  656. result.addInternalError(
  657. new(MultipleOfError),
  658. context,
  659. number,
  660. ErrorDetails{
  661. "multiple": new(big.Float).SetRat(currentSubSchema.multipleOf),
  662. },
  663. )
  664. }
  665. }
  666. //maximum & exclusiveMaximum:
  667. if currentSubSchema.maximum != nil {
  668. if float64Value.Cmp(currentSubSchema.maximum) == 1 {
  669. result.addInternalError(
  670. new(NumberLTEError),
  671. context,
  672. number,
  673. ErrorDetails{
  674. "max": new(big.Float).SetRat(currentSubSchema.maximum),
  675. },
  676. )
  677. }
  678. }
  679. if currentSubSchema.exclusiveMaximum != nil {
  680. if float64Value.Cmp(currentSubSchema.exclusiveMaximum) >= 0 {
  681. result.addInternalError(
  682. new(NumberLTError),
  683. context,
  684. number,
  685. ErrorDetails{
  686. "max": new(big.Float).SetRat(currentSubSchema.exclusiveMaximum),
  687. },
  688. )
  689. }
  690. }
  691. //minimum & exclusiveMinimum:
  692. if currentSubSchema.minimum != nil {
  693. if float64Value.Cmp(currentSubSchema.minimum) == -1 {
  694. result.addInternalError(
  695. new(NumberGTEError),
  696. context,
  697. number,
  698. ErrorDetails{
  699. "min": new(big.Float).SetRat(currentSubSchema.minimum),
  700. },
  701. )
  702. }
  703. }
  704. if currentSubSchema.exclusiveMinimum != nil {
  705. if float64Value.Cmp(currentSubSchema.exclusiveMinimum) <= 0 {
  706. result.addInternalError(
  707. new(NumberGTError),
  708. context,
  709. number,
  710. ErrorDetails{
  711. "min": new(big.Float).SetRat(currentSubSchema.exclusiveMinimum),
  712. },
  713. )
  714. }
  715. }
  716. // format
  717. if currentSubSchema.format != "" {
  718. if !FormatCheckers.IsFormat(currentSubSchema.format, float64Value) {
  719. result.addInternalError(
  720. new(DoesNotMatchFormatError),
  721. context,
  722. value,
  723. ErrorDetails{"format": currentSubSchema.format},
  724. )
  725. }
  726. }
  727. result.incrementScore()
  728. }