Module: sources/cores/cores

Export the Validator singleton instance that allow to validate complex data structure
Author:
License:
Source:

Example

const validator = Itee.Validators.Validator

 // Using unique function for One registered type
 // Usefull when a simple data structure is used multiple times
 validator.add( 'ColorType', color => {

 const r = color.r
 if ( color.r === undefined || Itee.Validators.isNotNumber( r ) ) {
 return false
 }

 const g = color.g
 if ( color.g === undefined || Itee.Validators.isNotNumber( g ) ) {
 return false
 }

 const b = color.b
 if ( color.b === undefined || Itee.Validators.isNotNumber( b ) ) {
 return false
 }

 return true
 } )

 // Using schema composition
 // Usefull for design validation schema faster and based on previous declared validation types
 validator.add( 'Range_0_255', ( value ) => {

 if ( Itee.Validators.isNotNumber( value ) ) {
 return false
 }

 return !(value <= 0 || value > 255)

 } )

 validator.add( 'ColorSchema', {
 r: {
 required: true,
 type:     'Range_0_255'
 },
 g: {
 required: true,
 type:     'Range_0_255'
 },
 b: {
 required: true,
 type:     'Range_0_255'
 }
 } )

 validator.add( 'ColorStructure', {
 color_from_type: {
 type: 'ColorType'
 },
 col_from_schema: {
 type: 'ColorSchema'
 },
 col_from_fn:     {
 // Inner function
 // Usefull for specific validation requirement that cannot match other previous validation schema or type
 fn: function ColorValidator ( color ) {

 const r = color.r
 if ( color.r === undefined || Itee.Validators.isNotNumber( r ) ) {
 return false
 }

 const g = color.g
 if ( color.g === undefined || Itee.Validators.isNotNumber( g ) ) {
 return false
 }

 const b = color.b
 if ( color.b === undefined || Itee.Validators.isNotNumber( b ) ) {
 return false
 }

 return true
 }
 }
 } )

 // The data to validate
 const colorStruct = {
 color_from_type: {
 r: 0,
 g: 1,
 b: 2
 },
 col_from_schema: {
 r: 10,
 g: 20,
 b: 30
 },
 col_from_fn:     {
 r: 0,
 g: 127,
 b: 255
 }
 }

 // Execute

 try {

 if ( validator.check( colorStruct, 'ColorStructure' ) ) {
 alert( 'ColorStructure is valid !' )
 } else {
 alert( validator.errors )
 }

 } catch ( err ) {
 alert( err )
 }

Members


<inner> validatorInstance :Validator

The singleton instance
Type:
  • Validator
Source: