Code coverage report for src/services/validator.js

Statements: 81.82% (18 / 22)      Branches: 71.43% (10 / 14)      Functions: 100% (2 / 2)      Lines: 81.82% (18 / 22)      Ignored: none     

All files » src/services/ » validator.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59    1   31                     31 89     89   89               89         89             89 89 89   89 4   89 89 28   89       31    
/*  Common code for validating a value against its form and schema definition */
/* global tv4 */
angular.module('schemaForm').factory('sfValidator', [function() {
 
  var validator = {};
 
  /**
   * Validate a value against its form definition and schema.
   * The value should either be of proper type or a string, some type
   * coercion is applied.
   *
   * @param {Object} form A merged form definition, i.e. one with a schema.
   * @param {Any} value the value to validate.
   * @return a tv4js result object.
   */
  validator.validate = function(form, value) {
    Iif (!form) {
      return {valid: true};
    }
    var schema = form.schema;
 
    Iif (!schema) {
      return {valid: true};
    }
 
    // Input of type text and textareas will give us a viewValue of ''
    // when empty, this is a valid value in a schema and does not count as something
    // that breaks validation of 'required'. But for our own sanity an empty field should
    // not validate if it's required.
    Iif (value === '') {
      value = undefined;
    }
 
    // Numbers fields will give a null value, which also means empty field
    Iif (form.type === 'number' && value === null) {
      value = undefined;
    }
 
    // Version 4 of JSON Schema has the required property not on the
    // property itself but on the wrapping object. Since we like to test
    // only this property we wrap it in a fake object.
    var wrap = {type: 'object', 'properties': {}};
    var propName = form.key[form.key.length - 1];
    wrap.properties[propName] = schema;
 
    if (form.required) {
      wrap.required = [propName];
    }
    var valueWrap = {};
    if (angular.isDefined(value)) {
      valueWrap[propName] = value;
    }
    return tv4.validateResult(valueWrap, wrap);
 
  };
 
  return validator;
}]);