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.
๐ Features
- โ Native HTML form validation
- โ Custom rules and messages per field
- โ
Live validation on
blur
andchange
- โ 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