Skema: Basic Validation

Example to show how to define a Type by Skema

by kaelzhang

HTML

<script src="https://unpkg.com/skema/umd/jsfiddle.js"></script>
<script src="https://unpkg.com/skema/umd/skema.min.js"></script>

JavaScript

const {type} = Skema

log('example 1')

const TypeNumber = type({
  // If the return value is
  // - true: pass the validation
  // - false: validation fails
  validate: v => typeof v === 'number'
})

success(TypeNumber.from(1))

throws(() => {
	TypeNumber.from('1')
})

log('example 2')

// You could just throw an error if something is wrong.
// With this mechanism,
// we could make our error reason verbose if necessary
const PositiveNumber = type({
  validate (v) {
    if (typeof v !== 'number') {
      return false
    }

    if (v > 0) {
      return true
    }

    // If the subject thrown is not an Error,
    // an Error will be created based on the subject
    throw 'must be positive'
  }
})

success(PositiveNumber.from(1))

throws(() => {
	PositiveNumber.from(-1)
})

log('example 3')

// Regular expression as a validator
const Alphabets = type({
  validate: /^[a-z]+$/i
})

success(Alphabets.from('abc'))

throws(() => {
	Alphabets.from('123')
})