A convenient approach to validating object properties in javascript. This method was built with an emphasis on validating function parameters passed as an object (object literal syntax).
npm install valid-param.js
- Visit https://cdnjs.com/libraries/valid-param.js
- Add CDN link to your site with <script>
- Download valid-param.min.js
- Add to your site with
<script>
valid-param.js was designed with the intent of validating function parameters passed as properties of an object, but can be used to validate properties of any object.
Simply call the ValidParam
class and pass in the parameters object as the first argument, along with a 'type assignment' object as the second argument. The 'type assignment' object associates each expected parameter with an acceptable type. If any parameter value is passed with an incorrect type, the appropriate error is thrown.
new ValidParam(parameters, {
name: 'string',
age: 'number',
})
The class is best used as the first bit of logic inside the function or method.
function getProfileBlock(parameters = {}) {
new ValidParam(parameters, {
name: 'string',
age: 'number',
})
return `${name}<br>${age}`
}
Parameter types are assigned inside of the 'type assignment' object. The key should refer to the paramenter name while the value refers to that parameter's type assignment.
{
age: 'number',
}
If you would like to assign a default type to non-typed parameters, you can you simply add a default
property to the 'type assignment' object.
{
age: 'number',
default: 'string'
}
Any parameter (or object-property) that is not explicitly typed in the 'type assignment' object will default to this setting. If a default is not set, all non-typed paramaters will be ignored.
To assign multiple acceptable types, simply separate each type with a |
mark.
{
age: 'string|number',
}
A parameter can be made nullable by simply adding the null
type to the assignment string.
{
age: 'string|number|null',
}
If there is only a single acceptable type, then you can simply add ?
at the beginning of the string.
{
age: '?string',
}
If a parameter can be of any type, including null
, programmers may use the mixed
or any
types. Either will allow any value through, regardless of type, as long as the parameter is defined.
{
age: 'mixed',
}
string
(orstr
)number
(ornum
,int
)boolean
(orbool
)array
(orarr
)object
(orobj
)mixed
(orany
)
Pull requests are welcomed to this project