Categories: CSSScriptWeb Design

Client-Side Declarative Form Validation using Strictly.js

Strictly.js is a JavaScript library that handles client-side form validation with minimal configuration.

Unlike bulky validation solutions, it weighs less than 5KB minified while providing comprehensive validation capabilities through HTML data attributes.

You use it to validate user input in real-time or on demand, handle various input types, and customize error feedback without writing complex validation logic in your JS files.

Features:

  • HTML Attribute-Based Rules: Define validation directly in your markup (data-strictly-*).
  • Sponsored
  • Real-time Feedback: Validate as users type (oninput) or just show errors (showerror).
  • Customizable Errors: Control error message placement, tag (div/p), and CSS classes.
  • Wide Input Support: Handles text, email, numbers (integer, digits, decimal), checkboxes, radio buttons, textareas, and select elements.
  • Advanced Validation Rules: Includes regex pattern matching, password complexity enforcement, and field comparison
  • Pattern & Password Validation: Supports regex and configurable password complexity rules.
  • Checkbox/Select Counts: Enforce min/max selections for checkboxes (by name) and multi-selects.
  • Length Constraints: Validate min/max characters or words.
  • Field Matching: Ensure one field’s value equals another (data-strictly-equalto).
  • Dynamic Element Handling: Automatically picks up and validates form fields added to the DOM later.
  • Detailed Validation Reports: Get comprehensive validation results including errors and form values.

How to use it:

1. Download and load the minified version of the Strictly.js library in the document.

<script src="strictly.min.js"></script>

2. Initialize the Strictly.js library and pass a CSS selector for the element(s) containing the inputs you want to validate. This can be a form, a div, or even a specific input.

const instance = new Strictly('.form', {

  // 'showerror' or 'oninput'
  restrict: 'showerror',

  // custom classes
  fieldErrorClass: 'strictly-validation-error',
  fieldSuccessClass: 'strictly-validation-success',
  errorClass: 'strictly-error-message',

  // 'p' or 'div'
  errorTag: 'p', // Allowed values: 

  // 'down', 'up', or 'custom'
  errorMessagePosition: 'down', 

  // CSS class of parent element if errorMessagePosition is 'custom'.
  errorCustomClass: null,

  // shows error immediately on input
  initError: true, 

});

3. Customize the styles of error/success states and error messages:

Sponsored
.strictly-validation-error {
  border: 1px solid #FF0000;
}

.strictly-validation-success {
  border: 1px solid #00FF00;
}

.strictly-error-message {
  font-size: 12px;
  color: #FF0000;
  font-weight: 500;
  text-transform: capitalize;
  margin: 4px 0;
}

4. Add validation rules directly to your HTML elements using the following HTML data attributes:

  • data-strictly-required="true|false": Explicitly mark a field as required or not required (overrides native `required`).
  • data-strictly-type="email|number|integer|digits|alphanum|alphanumspace|alphanumstrict|url": Specify the expected data format (use instead of or alongside `type` attribute for text inputs).
  • data-strictly-datetime="format": Validate specific date/time formats (e.g., “YYYY-MM-DD HH:mm”).
  • data-strictly-minlength="N": Enforce a minimum character length.
  • data-strictly-maxlength="N": Enforce a maximum character length.
  • data-strictly-length="[min, max]": Enforce a character length within a specific range.
  • data-strictly-min="N": Enforce a minimum numerical value.
  • data-strictly-max="N": Enforce a maximum numerical value.
  • data-strictly-range="[min, max]": Enforce a numerical value within a specific range.
  • data-strictly-pattern="regex": Validate input against a specified regular expression pattern.
  • data-strictly-password="rules": Enforce password complexity rules (e.g., “alpha:caps, num, min=8”).
  • data-strictly-mincheck="N": Require at least N checkboxes with the same `name` attribute to be checked.
  • data-strictly-maxcheck="N": Allow at most N checkboxes with the same `name` attribute to be checked.
  • data-strictly-check="[min, max]": Require the number of checked checkboxes (same `name`) to be within a range.
  • data-strictly-equalto="selector": Require the field’s value to match the value of another field identified by the CSS selector.
  • data-strictly-minwords="N": Require a minimum number of words.
  • data-strictly-maxwords="N": Allow a maximum number of words.
  • data-strictly-words="[min, max]": Require the word count to be within a specific range.
  • data-strictly-mincharacters="N": Require a minimum number of characters (similar to `minlength`).
  • data-strictly-maxcharacters="N": Allow a maximum number of characters (similar to `maxlength`).
  • data-strictly-characters="[min, max]": Require character count to be within a range (similar to `data-strictly-length`).
  • data-strictly-minselect="N": Require at least N options to be selected in a multi-select dropdown.
  • data-strictly-maxselect="N": Allow at most N options to be selected in a multi-select dropdown.
  • data-strictly-select="[min, max]": Require the number of selected options in a multi-select to be within a range.
  • data-strictly-initialnospace: Ensures input does not start with a space.
  • data-strictly-singlespace: Ensures only single spaces are allowed between words.
  • data-strictly-filetype: Allowed file types/extensions (comma-separated, e.g. image/png,.jpg)
  • data-strictly-filesize: Max size in bytes.
  • data-strictly-filecount: Min/max files.
  • data-strictly-custom: Custom form validation.
<h3>Basic Inputs</h3>
<div class="mb-3">
  <label for="field-1" class="form-label">Field 1</label>
  <input type="text" id="field-1" name="field1" class="form-control" data-strictly-maxlength="4" required>
</div>
<div class="mb-3">
  <label for="field-2" class="form-label">Field 2</label>
  <input type="text" id="field-2" name="field2" class="form-control" data-strictly-type="url" required>
</div>
<button id="subb" class="btn btn-primary">Validate</button>

5. Strictly.js provides a public method to trigger validation manually for all targeted elements.

const result = instance.validate({
  formError: true
});

Comparison with Alternatives

  • Native HTML5 Validation: Built-in browser validation is simple (required, type="email", pattern, minlength, etc.) but offers limited customization for error messages and styling across browsers. Strictly.js provides more rules out-of-the-box (like alphanumstrict, word counts, checkbox groups) and gives you full control over error display and styling via CSS classes and placement options. Strictly.js is preferable when you need consistent behavior and appearance, or more complex rules than HTML5 provides natively.
  • Parsley.js: Parsley is another popular library that also uses data-* attributes. It’s generally more feature-rich than Strictly.js, offering things like custom validators, internationalization (i18n), remote validation (AJAX), and potentially more complex grouping/dependency handling. Parsley might be a better choice for very complex forms or enterprise applications needing those advanced features. Strictly.js seems positioned as a simpler, more lightweight alternative focusing on the core attribute-based validation experience. If you just need solid validation without the extra bells and whistles (and potentially larger footprint) of Parsley, Strictly.js is a good fit.
  • jQuery Validate: A classic and very robust library, but it requires jQuery. Its syntax is primarily JavaScript-based (defining rules in JS objects), although it can read some HTML5 attributes. Strictly.js offers a more modern, dependency-free approach if you prefer defining rules directly in HTML. If you’re already using jQuery heavily, Validate is still a powerful option. If not, Strictly.js avoids adding that dependency.

Changelog:

v2.0.1 (07/11/2025)

  • Initial No Space Validation: New built-in rule data-strictly-initialnospace ensures input does not start with a space. Auto-corrects in restrict: ‘oninput’ mode.
  • Single Space Between Words Validation: New built-in rule data-strictly-singlespace ensures only single spaces are allowed between words. Auto-corrects in restrict: ‘oninput’ mode.
  • Custom Validator Auto-Correction: Custom validators can now return { valid: boolean, corrected: string } to support auto-correction in restrict: ‘oninput’ mode. Documented in README with example.
  • Async Validation Support: The validate() API is now always async and returns a Promise, even if all validators are synchronous. All validation code must use await or .then() to get results.
  • Debounced Live Validation: New debounce option (in ms) for live validation. When set, input validation is debounced for smoother UX and better performance. Documented in README with example.
  • File Input Validation: Added support for file input validation via data-strictly-filetype (allowed types/extensions), data-strictly-filesize (max size in bytes), and data-strictly-filecount (min/max files).
  • The errorPlacement callback option is now fully robust: StrictlyJS always creates an error element for each field and assigns it a unique id, even if errorPlacement is used.
  • The callback is responsible for placing the error element in the DOM, but the element will always be accessible by id for updates and clearing.
  • The callback should ensure the error element remains in the DOM for as long as errors need to be shown. If removed, StrictlyJS will re-create it as needed.
  • This makes custom error placement fully compatible with StrictlyJS’s internal update logic and enables advanced summary/error aggregation patterns.
  • StrictlyJS no longer submits forms natively on successful validation. The onSuccess callback is now the only place to handle what happens next (AJAX, custom logic, etc.).
  • If you want native submission, you must call form.submit() manually in onSuccess (not recommended for AJAX flows).
  • Required error messages are now only shown after the first focus, input, or blur, or on submit/API call. This improves UX by not showing errors on initial focus.

The post Client-Side Declarative Form Validation using Strictly.js appeared first on CSS Script.

rssfeeds-admin

Share
Published by
rssfeeds-admin

Recent Posts

Asus’ new open earbuds are a wonderful companion for handheld gaming

They look like your average open earbuds, but with optional RGB LED effects. | Photo…

11 minutes ago

A Look Back, March 14

200 Years Ago By virtue of a warrant from the selectmen of the town of…

28 minutes ago

Photos: Afternoon on the porch

Ally Connor, back, and Eva Dentremont, bottom, lounge with Lincoln on their porch as the…

29 minutes ago

Southampton may ask voters to approve override to restore Norris School positions

SOUTHAMPTON — Residents could again be asked to decide whether to approve a Proposition 2½ override…

29 minutes ago

Limericks, laughs and a few roasts at Northampton St. Patrick’s breakfast

NORTHAMPTON — From limericks to lighthearted jabs, the Hotel Northampton ballroom was transformed Friday morning…

29 minutes ago

Harvesting the sun: Easthampton’s Park Hill Orchards triple solar capacity with state energy grant

EASTHAMPTON — Surging energy costs put a strain on trying to power two large-scale food…

29 minutes ago

This website uses cookies.