JSPM

superform-validator

1.0.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 3
  • Score
    100M100P100Q33247F
  • License MIT

A powerful and flexible JavaScript form validator for HTML.

Package Exports

  • superform-validator
  • superform-validator/dist/form-validator.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (superform-validator) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

๐Ÿ“ฆ SuperForm Validator

A powerful and flexible JavaScript form validator for native HTML forms.

npm npm bundle size (version) GitHub release (by tag) jsDelivr hits (npm) npm GitHub issues GitHub closed issues


๐Ÿš€ Features

  • โœ… Native HTML form validation
  • โœ… Custom rules and messages per field
  • โœ… Live validation on blur and change
  • โœ… File input validation (max files, size, types)
  • โœ… Type casting (string, number, boolean, case conversions)
  • โœ… Auto-scroll to the first error
  • โœ… Custom error display element and CSS class
  • โœ… Easy reset and form clearing

Installation

To use FormValidator include form-validator.js just above closing body tag into html

  <script src="form-validator.js"></script>

OR use jsDeliver CDN

  <script src="https://cdn.jsdelivr.net/npm/superform-validator@1.0.1/dist/form-validator.js"></script>

OR use unpkg CDN

  <script src="https://unpkg.com/superform-validator@1.0.1/dist/form-validator.js"></script>

๐Ÿ› ๏ธ Initialization

const validator = FormValidator.init('#myForm', schema, onValid, onError, options);

Parameters:

Parameter Type Description
form String or DOM Element Form selector or DOM reference
schema Object Validation rules and casting for each field
onValid Function Callback when validation passes
onError Function Callback when validation fails
options Object Optional: custom error element and class

โš™๏ธ Options

Option Type Default Description
errorElement String 'div' HTML element to display error messages
errorClass String 'validation-error' CSS class for error elements

๐Ÿ“š Supported Rules

๐Ÿ“ Basic Rules

Rule Syntax Description
require require Field must not be empty
minLength minLength::int Minimum number of characters
maxLength maxLength::int Maximum number of characters
length length::int Exact length
email email Valid email address
pincode pincode Indian PIN code
pan pan Indian PAN card format
ifsc ifsc Indian IFSC code
alpha alpha Only alphabets
alphaspace alphaspace Alphabets and spaces
alphanum alphanum Alphabets and numbers
alphanumspace alphanumspace Alphabets, numbers, spaces
slug slug Valid slug
decimal decimal Decimal number
integer integer Integer number
match match::otherFieldName Must match another field
in in::val1,val2 Value must be in provided list
notIn notIn::val1,val2 Value must not be in provided list
eq eq::value Must be equal to provided value
notEq notEq::value Must not be equal to provided value
gt gt::value Greater than provided value
gte gte::value Greater than or equal to provided value
lt lt::value Less than provided value
lte lte::value Less than or equal to provided value
contains contains::text Must contain provided text
notContains notContains::text Must not contain provided text
startsWith startsWith::text Must start with provided text
notStartsWith notStartsWith::text Must not start with provided text
endsWith endsWith::text Must end with provided text
notEndsWith notEndsWith::text Must not end with provided text

๐Ÿ“‚ File Rules

Rule Syntax Description
file::maxFiles file::maxFiles(int) Maximum number of files
file::maxSize file::maxSize(2MB) Maximum file size (supports KB, MB, GB, TB)
file::accepts file::accepts(jpg|png|image/jpeg) Allowed file extensions or MIME types

๐Ÿ”ง Custom Rules

validator.addCustomRule('isEven', (value) => parseInt(value) % 2 === 0, 'Value must be even');

๐Ÿงช Custom Regex Example

const schema = {
  username: {
    custom: {
      pattern: /^[a-zA-Z0-9_]{5,15}$/,
      message: 'Username must be 5-15 characters and alphanumeric'
    }
  }
};

๐Ÿ”„ Casting Rules

Cast Description
trim Removes whitespace
integer Casts to integer
float Casts to float
boolean Casts to boolean
lowercase Converts to lowercase
uppercase Converts to uppercase
snakecase Converts to snake_case
kebabcase Converts to kebab-case
camelcase Converts to camelCase
pascalcase Converts to PascalCase
titlecase Converts to Title Case

Usage

HTML Form Mode

<form id="myForm">
  <input name="name" required />
  <input name="email" type="email" required />
  <button type="submit">Submit</button>
</form>
const validator = FormValidator.init('#myForm', {
  name: 'require|minLength::2',
  email: 'require|email',
});

validator.enableLiveValidation();

Example Schemas

const schema = {
  name: 'require|minLength::2|maxLength::50',
  email: {
    require: true,
    email: true,
    messages: {
      require: 'Email is mandatory.',
      email: 'Please enter a valid email address.'
    }
  }
}

๐Ÿ” Useful Methods

Method Description
validate() Validate the entire form
validateField(fieldName) Validate a single field
reset() Reset the form and clear errors
enableLiveValidation(eventsArray) Enable live validation on blur and change
addCustomRule(name, callback, message) Add your own validation rule

๐ŸŽฏ Example: Full Options

const validator = FormValidator.init('#myForm', {
  username: 'require|minLength::3|alphanum',
  password: {
    require: true,
    minLength: 6,
    messages: { minLength: 'Password must be at least 6 characters' },
    cast: 'trim'
  },
  profilePic: 'file::maxFiles(1)|file::accepts(jpg|png)'
}, (data) => {
  console.log('Form Valid!', data);
}, (errors) => {
  console.log('Form Errors', errors);
}, {
  errorElement: 'span',
  errorClass: 'input-error'
});

validator.enableLiveValidation();

๐Ÿ’ฌ Validation Message Templates

SuperForm Validator allows dynamic error messages using placeholders within message templates.

๐Ÿ”น Template Format:

@{placeholder}

๐Ÿ”น Available Placeholders:

Placeholder Description
@{field} The formatted field name (auto-converted to Title Case)
@{value} The actual input value
@{length} Length parameter for minLength, maxLength, length rules
@{listItems} For in or notIn rules: the allowed list
@{other} The compared value or label (for match, eq, gt, lt, etc.)
@{limit} Used in file rules for max files or size
@{types} Allowed file types for file::accepts

โœ… Example: Default Template Usage

const schema = {
  password: {
    require: true,
    minLength: 8 // Uses default message: "Minimum length is @{length}"
  }
}

If user enters a 5-character password, the displayed message will be:

Minimum length is 8

โœ… Example: Custom Template Message

const schema = {
  password: {
    require: true,
    minLength: {
      rule: 8,
      message: '@{field} must be at least @{length} characters long'
    }
  }
};

If user enters "abc", the displayed message will be:

Password must be at least 8 characters long

โœ… Example: File Rule Template

const schema = {
  profilePic: 'file::maxFiles(1)|file::accepts(jpg|png)'
}

If user uploads a .pdf file, the displayed message will be:

Invalid file type. Only (jpg, png) allowed

โœ”๏ธ The @{types} placeholder is replaced automatically.


โœ… Example: Field-Level Messages

You can override messages per field like this:

const schema = {
  email: {
    require: true,
    email: true,
    messages: {
      require: 'Email is mandatory',
      email: 'Please enter a valid email'
    }
  }
}

โœ”๏ธ Priority:

Field message > Inline message > Default system message


๐Ÿ“Œ Summary: Message Template Power

  • โœ… Clean, reusable, and consistent.
  • โœ… Easy to localize in the future.
  • โœ… Fully customizable per rule or per field.

๐Ÿ“œ License

Released under the MIT License


๐Ÿ‘จโ€๐Ÿ’ป Author

Made with โค๏ธ by Harshal Khairnar
Founder, Hitraa Technologies
๐Ÿ“ง harshal@hitraa.com