Security News
tea.xyz Spam Plagues npm and RubyGems Package Registries
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Readme
A validation library written for client/server side needs in javascript.
Installation
npm install iz --save
# or
yarn add iz
Then you can include iz, are and validators if needed
import iz from 'iz';
import are from 'iz/lib/are';
import validators from 'iz/lib/validators';
Once you do this, you can start validating. To do this, provide a value, any associated error messages and the validators. Here is a simple example:
import iz from 'iz';
import validators from 'iz/lib/validators';
iz({ value: 'Test', errorMessages: { string: 'Must be a string' }, validators}).string().valid;
If you'd like to do something more custom (to reduce bundle size):
import iz from 'iz';
import between from 'iz/lib/basicValidators/between';
import int from 'iz/lib/basicValidators/int';
function myCustomValidator { ... }
iz({ value: 4, validators: { between, int, myCustomValidator }}).string().valid;
Iz v2+ heavily relies on many es6 features including: promises, proxies, objects and arrays. You MUST polyfill proxy and promise, the other features will compile to es5. If something doesn't work please report it.
iz({ value: 10, validators }).between(2, 15).int().multiple(5); // why yes, yes it is
iz({ value: 10, validators }).notBetween(1, 5); // all validators (custom or not) have a not variant available
iz(), and all validation commands return an Iz object. An iz object always contains an errors
{array} and valid
{bool}. errors
will be filled with a default error messsage for each incorrect field. To provide custom error messages you can do the following:
var customErrorMessages = {
notBetween: 'Value must be between!',
int: 'Not an int!!!',
multiple: 'This is terrible and you should fix it'
}
iz({ value: 'Bob', errorMessages: customErrorMessages }).notBetween(2, 15).int().multiple(5);
It is often useful to get a list of validations from your server for a given model. Nested objects work to!
var rules = {
'cost': [
{
'rule': 'between',
'args': [17, 1000],
'error': 'The cost must be between 17, 1000'
},
{
'rule': 'required',
'error': 'You must specify a cost'
},
],
'producer.id': [
{
'rule': 'int',
'error': 'Producer ID must be an int'
}
],
'producer.name.first': [
{
'rule': 'alphaNumeric',
'error': 'Must be names and numbers'
}
]
};
are(rules, validators).for({
cost: 20,
producer: {
id: 1,
name: {
first: 'bob'
}
}
}).valid;
It is often useful to get back error messages from an Are object. You can use the "invalidFields" property to get back errorMessages.
var result = Are(...).for(someAttributeObject);
if (!result.valid) {
return rules.invalidFields;
}
You can create custom validations that run asynchronously. This works with both iz and are functions. IMPORTANT: If you have an async validator and don't use the async property, you'll get false positives.
const validators = {
unique: function() {
return fetch(...).then(() => true).catch(false);
}
};
iz({ value: 'name', validators }).unique().async.then((result) => {
result.valid; // can be true or false;
})
// we also support async/await
let result = await iz({ value: 'name', validators }).unique().async;
return result.valid;
let result = await are(...).for(obj).async;
return result.valid;
In the event you want to return more detailed error messages. You can use a simple syntax to format your error message with a validators arguments.
var errorMessages = {between: '{{0}} is not between {{1}} and {{2}}'};
var izObj = iz({ value: 5, errorMessages, validators }).between(100, 200);
console.log(izObj.errors);
will log ['5 is not between 100 and 200']
. This works with
are.getInvalidFields()
too.
In most cases, you'll only want to validate values when they exist. By default iz functions in this way. If you want to force the presence of a value you can use the required
method.
iz({ value, validators }).required() //a value is required
iz({ value, validators }).email().required() //value is required and is a valid email
iz({ value, validators }).date() //value is not required but must be a date if provided
All validators (apart from iz.required) return true if no value is provided (e.g. null, undefined or '').
Validations (true case in comments):
alphaNumeric(*); // Is number or string(contains only numbers or strings)
between(number, start, end); // Number is start or greater but less than or equal to end, all params numeric
blank(*); // Empty string
boolean(*); // true, false, 0, 1
cc(*); // Luhn checksum approved value
date(*); // Is a date obj or is a string that is easily converted to a date
decimal(*); // int or float
email(*); // Seems like a valid email address
empty(*); // If an object, array or function contains no properties true. All primitives return true.
equal(*, *); // Any 2 things are strictly equal. If 2 objects their internal properties will be checked. If the first parameter has an equals method that will be run instead
extension(ob1, ob2); // If obj2's methods are all found in obj1
fileExtension(value, arr); // Checks if the extension of value is in arr. An obj can be provide, but must have indexOf defined.
fileExtensionAudio(value); // Check against mp3, ogg, wav, aac
fileExtensionImage(value); // Check against png, jpg, jpeg, gif, bmp, svg, gif
inArray(value, arr); // If * is in the array
anArray(arr); // If arr is an array
int(*, bool (optional)); // Is an int. If the 2nd variable is true (false by default) a decimal is allowed
ip(str); // str resembles an IPV4 or IPV6 address
minLength(val, min); // val (str or arr) is greater than min
match(str, tester, flags?); // RegExp matching of a string. Accepts RegExps and strings as the tester
maxLength(val, max); // val (str or arr) is shorter than max
multipleInt(num, mult); // Int is multiple of another Int
multipleFloat(num, mult); // Float is multiple of another Float
number(*); // Is either an int or decimal
ofType(obj, typeName); // If it is a named object, and the name matches the string
phone(str, canHaveExtension?); // Is an american phone number. Any punctuations are allowed.
postal(*); // Is a postal code or zip code
required(*); // Is not null, undefined or an empty string
ssn(*); // Is a social security number
string(*); // Is the argument of type string
Almost all possible use cases that will definitely work (and definitely not work) are in the spec folder.
Add nested error rules within are. The current implementation doesn't allow for composition.
Goal: Allow for singleton free creation of Iz and Are objects. This is not a backwards compatible change. Many systems these days don't play nicely with singletons especially due to code splitting. This change should resolve that problem by required that Iz objects be supplied with validators. This also required the ordering of arguments supplied to Iz be modified. Click here for docs on the old "register" system if you're using v2.
Summary:
Goals - Modernize, make the library smaller and add more features.
New features:
Improvements:
Other:
iz.addValidator
method to add custom validations more effectivelyis.anArray
validation_fields
variable in Are to fields
getInvalidFields
to Areiz.string
validation.required
FAQs
Validation for node and the web.
The npm package iz receives a total of 1,223 weekly downloads. As such, iz popularity was classified as popular.
We found that iz demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.
Security News
UnitedHealth Group disclosed that the ransomware attack on Change Healthcare compromised protected health information for millions in the U.S., with estimated costs to the company expected to reach $1 billion.