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
}
}
}
}