Package detail

nemo-validator

anandnic220MIT1.0.0

A lightweight class-based form validation library for web applications

validation, form, input, validator

readme

Nemo Validator

A lightweight JavaScript class-based form validation library that helps validate different types of inputs in web forms at the event level.

Features

  • Easy to set up and use with any HTML form
  • Real-time validation with immediate feedback
  • Strict input filtering that blocks invalid characters at the keyboard event level
  • Strict decimal place validation - prevents typing beyond 2 decimal places
  • Pre-built validation rules for common inputs (email, mobile, PAN, GST, etc.)
  • Ability to add custom validation rules with event handling
  • Pure JavaScript with no dependencies
  • Lightweight and performance-optimized

Installation

Install the package using npm:

npm install nemo-validator

Or using yarn:

yarn add nemo-validator

Basic Usage

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Nemo Validator Example</title>
    <style>
        .text-danger {
            color: red;
            font-size: 0.8rem;
            margin-top: 5px;
            display: block;
        }
    </style>
</head>
<body>
    <form class="nemo-validate-form">
        <div>
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" class="validate-name">
        </div>

        <div>
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" class="validate-email">
        </div>

        <div>
            <label for="mobile">Mobile:</label>
            <input type="text" id="mobile" name="mobile" class="validate-mobile">
        </div>

        <div>
            <label for="amount">Amount:</label>
            <input type="text" id="amount" name="amount" class="validate-two-decimal" placeholder="Enter amount (e.g., 123.45)">
            <!-- Strictly blocks input after 2 decimal places -->
        </div>

        <button type="submit">Submit Form</button>
    </form>

    <script src="node_modules/nemo-validator/dist/index.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize the validator
            const validator = new NemoValidator('nemo-validate-form');

            // Store validator instance for features
            window.nemoValidatorInstance = validator;

            // Validate form on submit
            document.querySelector('.nemo-validate-form').addEventListener('submit', function(e) {
                if (!validator.nemoValidateInputs()) {
                    e.preventDefault();
                    alert('Please fix the errors in the form.');
                }
            });
        });
    </script>
</body>
</html>

ES Module Usage

import NemoValidator from 'nemo-validator';

document.addEventListener('DOMContentLoaded', function() {
    // Initialize with default rules
    const validator = new NemoValidator('nemo-validate-form');

    // Store validator instance for features
    window.nemoValidatorInstance = validator;

    // Add a custom validation rule
    validator.addRule('validate-password', {
        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/,
        message: 'Password must be at least 8 characters, include uppercase, lowercase and a number.',
        filterPattern: /[^\w!@#$%^&*()]/g
    });

    // Validate all inputs when form is submitted
    document.querySelector('.nemo-validate-form').addEventListener('submit', function(e) {
        if (!validator.nemoValidateInputs()) {
            e.preventDefault();
            console.log('Form has validation errors');
        }
    });
});

Available Validation Rules

Rule Class Validates Description
validate-name Names Letters, spaces, dots
validate-mobile Mobile numbers 10-digit format
validate-aadhar Aadhar numbers 12-digit format
validate-pan PAN card numbers Format: ABCDE1234F
validate-email Email addresses Standard email format
validate-address Addresses Letters, numbers, spaces, dots, forward slash
validate-pin PIN codes 6-digit format
validate-text Text Letters, spaces, dots, forward slash
validate-numeric Numbers Digits only
validate-business Business names Letters, numbers, spaces, dots, forward slash
validate-gst GST numbers Format: 22AAAAA0000A1Z5
validate-uam UAM numbers Format: DL05A1234567
validate-udyam UDYAM numbers Format: UDYAM-XX-00-0000000
validate-amount Amounts Strictly blocks typing beyond 2 decimal places at the event level
validate-two-decimal Amounts Strictly blocks typing beyond 2 decimal places without using data attributes
validate-strong-password Passwords Minimum 8 characters with uppercase, lowercase, number and special character
validate-age Age Numbers between 18-100 with auto-constraints
validate-credit-card Credit Cards Auto-formats with spaces after every 4 digits

Key Validation Behavior

Strict Decimal Place Validation

Nemo Validator implements strict decimal place validation that:

  • Blocks typing beyond the decimal limit at the keydown event level
  • Prevents invalid input directly during the typing process
  • Handles all validation events (keydown, paste, input) to ensure completeness
  • Preserves cursor position after formatting

Example usage (as shown in the example files):

<!-- For amounts with up to 2 decimal places -->
<input type="text" id="amount" name="amount" class="validate-two-decimal" placeholder="Enter amount (e.g., 123.45)">

API Reference

Constructor

const validator = new NemoValidator(formClass, customRules);
  • formClass: CSS class of the form(s) to validate
  • customRules: (Optional) Object containing custom validation rules

Methods

init()

Initializes the validator on the specified forms.

nemoValidateInputs()

Validates all inputs in the form and returns a boolean indicating if all inputs are valid.

Example:

// Initialize the validator
const validator = new NemoValidator('nemo-validate-form');

// Validate on form submission
document.querySelector('.nemo-validate-form').addEventListener('submit', function(e) {
    // Check if all inputs are valid
    if (!validator.nemoValidateInputs()) {
        // Prevent form submission if validation fails
        e.preventDefault();
        console.log('Form has validation errors');
    } else {
        console.log('All inputs are valid, proceeding with form submission');
        // submit the form here 
    }
});

validateField(element)

Validates a single input field and shows/hides error messages.

  • element: DOM element to validate

Example:

// Get a reference to the input element
const amountInput = document.getElementById('amount');

amountInput.addEventListener('blur', function() {
    // Call the validator to check the field
    const isValid = validator.validateField(this);

    if (isValid) {
        console.log('Amount field is valid');
    } else {
        console.log('Amount field has validation errors');
    }
});

addRule(name, rule)

Adds a custom validation rule.

  • name: Name of the rule (prefix 'validate-' optional)
  • rule: Object containing the rule details
    • pattern: RegExp pattern to test against
    • message: Error message to display
    • filterPattern: RegExp pattern to filter input (optional)
    • maxLength: Maximum input length (optional)
    • setupEvents: Function to set up custom event handlers (optional)
    • customValidation: Function for custom validation logic (optional)

Example:

// Simplified custom rule that shows all available options
validator.addRule('my-decimal', {
    // Basic validation pattern - allows exactly 2 decimal places
    pattern: /^\d+\.\d{2}$/,

    // Custom error message
    message: 'Please enter a number with exactly 2 decimal places',

    // Auto-filter out non-digits and extra dots
    filterPattern: /[^\d.]/g,

    // Maximum length constraint
    maxLength: 10,

    // Custom event handling 
    setupEvents: function(element) {

        let lastValidValue = '';
        const isValidInput = (value) => {
            // Allow empty value or valid pattern 
            return !value || /^\d*\.?\d{0,2}$/.test(value);
        };


        element.addEventListener('keydown', function(e) {
            // Allow navigation keys
            if (e.key === 'Backspace' || e.key === 'Delete' || 
                e.key === 'ArrowLeft' || e.key === 'ArrowRight' || 
                e.key === 'Tab' || e.key === 'Home' || e.key === 'End' || 
                e.ctrlKey || e.altKey || e.metaKey) {
                return;
            }

            const newValue = this.value.substring(0, this.selectionStart) + 
                             e.key + 
                             this.value.substring(this.selectionEnd);

            if (!isValidInput(newValue)) {
                e.preventDefault();
            }
        });

        element.addEventListener('input', function() {
            if (isValidInput(this.value)) {
                lastValidValue = this.value;
            } else {

                this.value = lastValidValue;
            }
        });


        element.addEventListener('paste', function(e) {
            const pastedText = (e.clipboardData || window.clipboardData).getData('text');
            const newValue = this.value.substring(0, this.selectionStart) + 
                             pastedText + 
                             this.value.substring(this.selectionEnd);

            if (!isValidInput(newValue)) {
                e.preventDefault();
            }
        });
    },

    // Custom validation that runs during form validation
    customValidation: function(value) {
        if (!value) return false;

        // Convert to number and check range
        const num = parseFloat(value);

        if (num < 0.01) {
            this.message = 'Value must be at least 0.01';
            return false;
        }

        if (num > 999.99) {
            this.message = 'Value cannot exceed 999.99';
            return false;
        }

        return true;
    }
});

// Use this rule in HTML
// <input type="text" class="validate-my-decimal" placeholder="123.45">

removeRule(name)

Removes a validation rule.

  • name: Name of the rule to remove

Example:

// Remove the built-in PAN validation rule
validator.removeRule('validate-pan');

// Or remove a custom rule
validator.removeRule('validate-indian-mobile');

console.log('The rule has been removed and will no longer be applied');

getRules()

Gets all validation rules.

  • Returns: Object containing all validation rules

Example:

// Get all current validation rules
const allRules = validator.getRules();

// Log rules to console
console.log('Available validation rules:', allRules);

// check if a specific rule exists
if (allRules['validate-email']) {
    console.log('Email validation rule exists with pattern:', allRules['validate-email'].pattern);
}

// iterate through all rules
Object.keys(allRules).forEach(ruleName => {
    console.log(`Rule: ${ruleName}, Message: ${allRules[ruleName].message}`);
});

Creating Custom Rules with Validation

// Custom rule with decimal validation
const myCustomRules = {
  'validate-custom-decimal': {
    pattern: /^[0-9]+(\.[0-9]{0,2})?$/,
    message: 'Please enter a valid number with up to 2 decimal places',
    filterPattern: /[^0-9.]/g,
    setupEvents: function(element) {
      // Setup custom event handlers
      element.addEventListener('keydown', function(e) {
        // Custom logic here
      });

      element.addEventListener('input', function() {
        // Custom input handling
      });
    }
  }
};

// Initialize with custom rules
const validator = new NemoValidator('my-form', myCustomRules);

Browser Compatibility

Nemo Validator works in all modern browsers:

  • Chrome, Firefox, Safari, Edge (latest versions)
  • IE11 with appropriate polyfills

License

MIT