Skip to content

Instantly share code, notes, and snippets.

@bvaughn
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bvaughn/7db78c3e8639f8613a63 to your computer and use it in GitHub Desktop.
Save bvaughn/7db78c3e8639f8613a63 to your computer and use it in GitHub Desktop.
forms-js validation schema (proposal 1)

Validation example for the form shown here: http://jeremydorn.com/json-editor/

Assuming all of the fields in the form you linked to are required, I'll start by showing what formFor validation rules would look like:

{
  name: {
    required: true
  },
  age: {
    required: true
    type: 'positive integer'
  },
  favorite_color: {
    required: true
    pattern: /^#{0,1}[0-9A-F]{3,6}$/
  },
  gender: {
    required: true
    pattern: /^(male|female)$/
  },
  location: {
    city: {
      required: true,
    },
    state: {
      required: true,
      minlength: 2,
      maxlength: 2
    }
    /* No validation rules for :citystate because that's not really related to validation-step */
  },
  pets: {
    collection: {
      min: {
        rule: 1 // For example, we could require at least 1 pet
      },
      max: {
        rule: 4 // And allow no more than 4 (because really, that's too many pets)
      },
      fields: {
        name: {
          required: true
        }
      }
    }
  }
}

I think we could do better than formFor though, if we're aiming for ES6-compatibility.

For example, we could add support for things like:

  • type: Primatives use typeof (e.g. typeof VARIABLE === "string") whereas Objects could use instanceof (e.g. VARIABLE instanceof Hexadecimal).
  • constraints: Could support additional constraints for primative types. e.g. "number" types could be further scoped by the expression VALUE > 0
  • enum: Could support basic enumerations (assuming they work with equality operator). e.g. a "string" type could have an enum ['male', 'female']
{
  name: {
    required: true,
    type: 'string' 
  },
  age: {
    required: true,
    type: 'number',
    constraints: {
      operator: '> 0'
    }
  },
  favorite_color: {
    required: true,
    type: Hexadecimal // This is a fictional class ;)
  },
  gender: {
    required: true,
    type: 'string',
    constraints: {
      enum: ['male', 'female']
    }
  },
  location: {
    city: {
      required: true,
      type: 'string'
    },
    state: {
      required: true,
      type: 'string',
      constraints: {
        minlength: 2,
        maxlength: 2
      }
    }
  },
  pets: {
    type: Array,
    constraints: {
      minlength: 1, // For example, we could require at least 1 pet
      maxlength: 4  // And allow no more than 4 (because really, that's too many pets)
    },
    attributes: {
      name: {
        required: true
      }
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment