A simple, reactive schema validation smart package for Meteor.
When using check to validate, the Match.Error that is thrown now explains which field failed to validate and why (only the first error). All errors can be found in an invalidKeys property on the Match.Error object.
Bug fixes and MongoDB 2.6+ compatibility fixes
- Fix "undefined is not allowed by the schema" error message
- Trim strings before removing empty strings so that
" "will be cleaned - Don't type convert $unset values when cleaning
Added built-in regular expression SimpleSchema.RegEx.ZipCode
- The
cleanfunction now automatically converts a number or string to a Date object. (Thanks @rlora) - Fix to
makeGenerichandling when a property name starts with a number but also includes non-numeric characters. (Thanks @Nieziemski) - New
exclusiveMaxandexclusiveMinoptions allow you to specify that theminormaxvalue itself should not be considered valid. (Thanks @sleiber)
- Introduce the
pickmethod onSimpleSchemainstances to create subschemas - Fixed
minDatedefault validation error message - Fix issue where
customfunctions were not run if the operator was $unset or $rename
Fix blackbox handling during filtering (thanks @wojtkowiak)
Fix label reactivity when calling label method with a key that contains a specific index piece (like ".0.")
Minor fix
- Internal support for specifying many of the schema options as functions. Still largely untested, so not yet documented.
- Removed some API functions from the
SimpleSchemaprototype:requiredObjectKeys,requiredSchemaKeys,firstLevelSchemaKeys,customObjectKeys. If you were using them, you should be able to use the newobjectKeysfunction instead. - When you filter an object by calling
mySimpleSchema.cleanwith thefilter: trueoption, it no longer filters out$unsetkeys that aren't defined in the schema. This is helpful in a case where you've changed the schema, removing a key, and now you want to run some conversion code to unset that key in documents where it already exists. - Calling
mySimpleSchema.cleannow trims string values by default. To skip this, use thetrimStrings: falseoption when you callclean. You can also settrim: falsefor any key in the schema definition to indicate that string values for that key must never be trimmed. This is useful for a property that stores a password or markdown or anything else where leading and trailing spaces may matter. - Added
getErrorObjectfunction toSimpleSchemaValidationContextprototype. Mainly intended to be used by collection2 and autoform packages, but can be used anywhere you want to have anErrorobject that reflects the invalid schema context. - Made
blackbox: truework (and apply to all array item objects) whentype: [Object]. - Bump to 1.0.0 version to begin following semantic versioning standards more precisely.
BREAKING CHANGES!
SimpleSchema.RegEx.WeakEmailhas been removed, andSimpleSchema.RegEx.Emailis now the regular expression recommended by W3C here. This is a very permissive expression used by most browsers whentype=email.- Empty strings no longer cause a "required" error. If you don't want empty strings to be considered valid for a required key, be sure to clean your object before validating it.
- Fixed issue where
$setting an object property to an object that does not include all required properties was incorrectly considered to be valid.
BREAKING CHANGES!
regExmessages must now be defined in a different way. Refer to the README.- Removed support for
valueIsAllowedoption. Usecustominstead. - Remove
SchemaRegExexported variable. UseSimpleSchema.RegExinstead. - Internal code reorg and cleanup
- When
removeEmptyStringsoption is enabled during cleaning, empty strings in$setare now translated to$unset. $pulloperators that include aquery2are now properly cleaned
Console logging about filtered and autoconverted fields now happens only when SimpleSchema.debug = true
- Additional built-in RegEx patterns, including an alternative e-mail pattern. See the readme. (Thanks @Nemo64)
SimpleSchema.cleannow removes empty string values by default. To prevent this, set theremoveEmptyStringsoption tofalse.
Add built-in regular expression SimpleSchema.RegEx.Id for id's generated by Random.id() of the random package, and also usable to validate a relation _id.
- Add
SimpleSchemaValidationContext.prototype.addInvalidKeys. See "Manually Adding a Validation Error" in the README. - Fix minor issues with filtering
Internal change: Add keepArrays option to mongoObject.getFlatObject, for use by autoform pkg.
Fix issue with setting autoValue for property of an object that's in an array, when cleaning a modifier.
Fix issue where blackbox objects were being validated in update modifiers. (Thanks @Pugio!)
Fix issue where some implied schema keys were not automatically added to complex schema definitions
- Ensure that custom validation functions are always called in even more situations, but make sure that this doesn't cause unnecessary "required" errors.
- Add some
console.infoto help you see what is filtered out and autoconverted by thecleanmethod.
Fix issue where default values were being added to update modifiers.
Ensure custom validation functions are always called, even when the field is undefined.
Added userId or null to custom validation and autoValue contexts when on the client.
Generate auto values after type conversion so that autoValue functions don't have to handle type conversion. (Thanks @mjgallag!)
Fix issue with autoValue and defaultValue altering some updates.
autoValueoption moved from Collection2 package to SimpleSchemadefaultValueoption added- Significant rewrite of
MongoObject(used internally), which results in fixing some obscure bugs and hopefully not creating any new ones. cleannow does everything on the referenced object without cloning it. If this is not what you want, then you should pass in a clone of the object you want to protect and grab the resulting cleaned object from the return value.- All types of custom validation functions now have the same
thiscontext. siblingField()method now available inthiswithin bothautoValueand custom validation functions.this.userIdis potentially available in custom validation functions. You must pass it tovalidateorvalidateOnein theextendedCustomContextoption. Validation as part of Collection2 operations or AutoForm submissions provides this automatically.
Fix a small issue with debug option.
You can now set SimpleSchema.debug = true to cause all named validation
contexts to automatically log all invalid key errors to the browser console.
This can be helpful while developing an app to figure out why certain
actions are failing validation.
- Fix an issue where properties could be removed during cleaning because they start with the same string of characters as an invalid property.
- When determining which error message to display, we now look for the generic key after the specific key. For example, the error message for "addresses.$.street" will now be used for an error involving "addresses.0.street" when there is no specific error message for "addresses.0.street".
label method now works correctly when passing in specific array keys, e.g.,
array.0.name as opposed to array.$.name
- Fix validation of
blackboxobjects - Fix
labelsmethod - Messages and labels are now reactive
- Add support for
blackboxoption. See README - Ensure that NaN isn't considered a valid number
- When combining and extending SimpleSchema instances, the individual field definitions are now extended, meaning that you can add or override the schema options for an already-defined schema key.
- Error messages can now be defined globally using
SimpleSchema.messages(). Instance-specific messages are still supported and are given precedence over global messages. - The
labeloption can now be a function that returns a string. Whenever you need a schema key's label, use the newmySchema.label(key)method to get it. - Support
customoption. This will likely replacevalueIsAllowedeventually. Refer to "Custom Validation" and "Validating One Key Against Another" sections in the README.
Made a change that fixes an issue with the autoform package. When you specified
a doc attribute for an autoform and that document was retrieved from a
collection that had helpers attached using the collection-helpers package,
the autoform fields were not populated with the values from the document. Now
they are.
- Autoconvert to numbers from strings using
Number()instead ofparseFloat(). - Minor improvements to validation logic.
- README additions
Remove automatic call to clean when validating. This has no effect on
validation done through a collection with the collection2 package. However,
validation done directly with a SimpleSchema instance will now catch more
schema issues than it previously did (since 0.2.18).
Clone schema argument before modifying it
Fix basic object checking for IE 8
Complete rewrite of the internal validation logic. This solves some sticky
issues with array validation in more complex objects. It should not affect
the API or validation results, but you may notice some additional or slightly
different validation errors. Also, if you make use of the internally cached
copy of the schema definitions (ss._schema or ss.schema()), you may notice
some differences there.
The main change internally is that an array definition is now split into two definitions. For example, if your schema is:
{
myArray: {
type: [String]
}
}It is internally split and stored as:
{
myArray: {
type: Array
},
'myArray.$': {
type: String
}
}- Correctly validate $inc operator
- Allow passing an array of schemas to SimpleSchema constructor, which merges them to create the actual schema definition.
Fix an issue, introduced in 0.2.21, that prevented autoconversion of values in arrays.
Add tests for MongoObject and fix some issues found by the tests.
Fix an issue where cleaning a doc would convert empty arrays to empty strings.
Improve and export MongoObject class for use by collection2 and others.
Make sure min/max string length settings are respected when there is also a regEx option specified.
- Add support for named contexts. Use
mySimpleSchema.namedContext(name)method to access the named context, creating it if it does not exist yet. - The
validateandvalidateOnemethods on a SimpleSchema context now clean (filter and autoconvert) the doc before validating it. You should no longer call thecleanmethod yourself before validating. If you do have a good reason to call thecleanmethod before callingvalidateorvalidateOne, then set thefilterandautoConvertoptions tofalsewhen callingvalidateorvalidateOneto prevent double cleaning. - The
validateandvalidateOnemethods on a SimpleSchema context now returntrueorfalseto indicate the validity of the document or field, respectively. You do not need to call a separate method to check validity.
Throw an error when the modifier is an empty object for an update or upsert.
This prevents overwriting the entire document with nothing, leaving only
an _id field left.
Fix handling of min or max when set to 0.
Adjust handling of validation errors for arrays of objects. Now when a validation
error is added to the list for a property of an object that is a member of an
array, the key name is listed with the array index instead of a dollar sign. For
example, friends.0.name instead of friends.$.name.
- Ensure valueIsAllowed function is called for undefined and null values. This
change means that you must not ensure that your valueIsAllowed function returns
true when the value is
nullorundefined, if you want the field to be optional. - Fix an issue with false "required" errors for some arrays of objects when validating a modifier.
Fix $pullAll and clean $pushAll by converting it to $push+$each rather than deleting it.
Add workaround for Safari bug.
Clean method should now clean everything.
Validate upserts
Fix validation of required subobjects when omitted from a $set
- Add label inflection and allow labels to be changed dynamically with
labelsmethod. - Allow min and max to be a function that returns a min/max value
- Allow array of regEx with specific messages for each
Refactor validation loop to improve and not use collapse/expand
Add subschema support (@sbking) and use Match.Any for type schema key test
Fix validation of $push or $addToSet for non-objects
Fix validation of objects as values of modifier keys
Fix validation of custom objects
Fix validation of arrays of objects
Fix minor issues related to $unset key validation
(Backwards compatibility break!)
- Validation contexts are now supported, allowing you to track validity separately for multiple objects that use the same SimpleSchema
- Some of the API has changed, related to the support for validation contexts
- All mongo modifier operators are now recognized and properly validated; as part of this, you must now tell the validation functions whether you are passing them a normal object or a mongo modifier object
- Validation errors are now thrown if fields not allowed by the schema are present in the object
- When you create a schema, your definition object is now checked to make sure you didn't misspell any of the rules
- A SimpleSchema object is now a valid second parameter for the built-in
checkandMatch.testfunctions .match()method is deprecated
Return true from match()
Fix issue where filter() could strip out $ keys
Support custom validation functions (used by collection2 package)
Pass doc to valueIsAllowed function so that validating one key against another is possible
Deprecated the regExMessage key in schema definition and replaced with the ability to customize all validation error messages per error type and per schema key if necessary. Refer to the Read Me.