Iodine.js

repository·master·Indexed 19 days ago

https://github.com/caneara/iodine

A micro client-side validation library with no dependencies. It supports single-item and multi-item validation, chainable rules, and custom error messaging. Version 8.5.0 introduces major breaking changes from version 7. Features include assert[Rule] methods for simple checks, a flexible assert method for multiple criteria, and the ability to create custom validation rules via the rule() method.

Tokens
5.6K
Snippets
22
Records
23
Agent score
18%

What's inside @caneara/iodine

  1. How multiple item checks work for forms or objects

    master

    To validate multiple items (like form fields) at once, call assert with two objects.

    Parameters:

    1. An object where keys are field names and values are the items to validate.
    2. An object where keys are field names and values are arrays of rule strings.

    Return Value: Returns a report object containing a top-level valid boolean and a fields object containing sub-reports for each item. Each sub-report follows the same structure as a single item check.

    const items = {
        name     : 5,
        email    : 'test@example.com',
        password : 'abcdefgh',
    };
    
    const rules = {
        name     : ['required', 'string'],
        email    : ['required', 'email'],
        password : ['required'],
    };
    
    const report = Iodine.assert(items, rules);
    // report.valid will be false because 'name' is not a string
    // report.fields.name will contain the error details
  2. Handling asynchronous validation logic

    master

    Iodine does not support asynchronous custom rules (e.g., using async/await inside a rule closure).

    Recommended Pattern: Perform your asynchronous operations (like database lookups or API calls) before calling Iodine. Store the result of the async operation and then pass that result into Iodine for validation.

  3. How single item checks work with multiple rules

    master

    To test a single item against multiple criteria, use the assert method.

    Parameters:

    1. The item to check.
    2. An array of rule strings.

    Return Value: Unlike individual assertion methods, assert returns a report object:

    • If valid: { valid: true, rule: '', error: '' }
    • If invalid: { valid: false, rule: 'ruleName', error: 'Error message' }

    Important: If you want to allow for optional values, the 'optional' rule must be the first rule in the array.

    let item_1 = 7;
    let item_2 = 'string';
    
    // Returns report object
    Iodine.assert(item_1, ['required', 'integer']);
    Iodine.assert(item_2, ['required', 'integer']);
    
    // Using optional rule (must be first)
    let item_3 = null;
    Iodine.assert(item_3, ['optional', 'integer']);
  4. Handle optional values in multiple checks

    master

    To allow a value to be null, undefined, or an empty string while still applying other rules if a value is present, use the optional rule.

    Important: The 'optional' rule must be the first rule in the array.

    let item_2 = null;
    
    // Passing 'optional' as the first rule allows null to pass
    Iodine.is(item_2, ['optional', 'integer']); // true
  5. Install Iodine via CDN or NPM

    master

    You can include Iodine in your project using a CDN or by installing it via NPM.

    CDN usage: Add the script tag to your HTML. Ensure you use the correct version number in the URL.

    NPM usage: Install the package using your preferred package manager.

    Note on Upgrading: Version 8+ contains major breaking changes from version 7. Use version 8+ for new projects and stick to version 7 for existing legacy projects.

    <!-- CDN -->
    <script src="https://cdn.jsdelivr.net/npm/@caneara/iodine@8.5.0/dist/iodine.min.umd.js" defer></script>
    
    <!-- NPM -->
    npm i @caneara/iodine
  6. Initialize Iodine

    master

    If you are using a CDN, Iodine is automatically added to the window namespace and is available globally.

    If you are using a module bundler or want to create a specific instance, import Iodine and instantiate it with new Iodine().

    import Iodine from '@caneara/iodine';
    
    const instance = new Iodine();
  7. Initialize Iodine in your project

    master

    Depending on your environment, you can access Iodine in two ways:

    1. Browser (No build step): Iodine is automatically added to the window namespace.
    2. Module/Build Tool: Import Iodine from the package and instantiate it.
    import { Iodine } from '@kingshott/iodine';
    
    const iodine = new Iodine();
  8. Install the legacy Iodine library

    master

    You can install the legacy version of Iodine via CDN or NPM.

    Note: This documentation refers to a deprecated version of Iodine. For new projects, use the latest version from the main README.md.

    <script src="https://cdn.jsdelivr.net/npm/@kingshott/iodine@7.0.2/dist/iodine.min.umd.js" defer></script>
    npm i @kingshott/iodine
  9. Validate an object against a schema

    master

    Use isValidSchema(data, schema) to validate an entire object. The schema object maps keys to arrays of rules. This method returns a boolean.

    Iodine.isValidSchema({
        email    : 'welcome@to.iodine',
        password : 'abcdefgh',
        fullname : 'John Doe',
    }, {
        email    : ['required', 'email'],
        password : ['required', 'minLength:6'],
        fullname : ['required', 'minLength:3'],
    }); // true
  10. Retrieve and customize error messages

    master

    Iodine provides default English error messages.

    Get an error message

    Use getErrorMessage(rule, [params]). You can pass parameters as a combined string ('min:7') or as separate arguments ('min', 7). You can also pass an object to inject field names or parameters into the message.

    Localisation and Customization

    • Replace all messages: Use setErrorMessages({ ruleName: 'message' }). Use [FIELD] and [PARAM] placeholders for dynamic values.
    • Update a single message: Use setErrorMessage(ruleName, message).
    • Change default field name: Use setDefaultFieldName('New Name') (defaults to 'Value').
    // Get message
    Iodine.getErrorMessage('min:7', { field: 'age' });
    
    // Localisation
    Iodine.setErrorMessages({ same: "Champ doit être '[PARAM]'" });
    
    // Single update
    Iodine.setErrorMessage("passwordConfirmation", "Does not match password");
  11. Pass parameters to validation rules

    master

    Some rules require additional parameters (e.g., min, max, length). You can provide these in two ways when using the assert method:

    1. String syntax: Append the parameter to the rule string using a semicolon (e.g., 'min:5').
    2. Object syntax: Provide an object within the rules array specifying the rule and the param.
    // String syntax
    Iodine.assert(item, ['required', 'integer', 'min:5']);
    
    // Object syntax
    Iodine.assert(8, ['required', 'integer', { rule : 'min', param : 7 }, 'max:10']);
  12. Set custom error messages for rules

    master

    You can define specific error messages for your custom rules using setErrorMessage. Use the placeholder [FIELD] for the field name and [PARAM] for any parameter passed to the rule.

    Iodine.rule('equals', (value, param) => value == param);
    Iodine.setErrorMessage('equals', "[FIELD] must be equal to '[PARAM]'");