Git Product home page Git Product logo

jenkinsdev / validatinator Goto Github PK

View Code? Open in Web Editor NEW
107.0 10.0 10.0 10.48 MB

Validatinator is a simple, yet effective, HTML form validation library built for JavaScript/Typescript. Validatinator was originally loosely based off of Laravel's validation system.

Home Page: https://jenkinsdev.github.io/Validatinator/

License: MIT License

JavaScript 0.73% TypeScript 99.27%
javascript vanilla vanilla-js form-validation form-validator library typescript validation validator vanilla-ts

validatinator's Introduction

Validatinator (Reborn)

Current Release: 2.0.8 [Reborn]

Validatinator is a simple, yet effective, HTML form validation library built for JavaScript/TypeScript.

The project was originally loosely based off of Laravel's validation system, and has evolved since.

How to Use

Installation

npm install validatinator

Example Usage

import { Validatinator } from "validatinator";

const validatinator = new Validatinator({
  ".my-form-query-selector": {
    ".my-field-query-selector": "required|alpha",
    ".another-field": "min:3|max:10",
    "input[type='checkbox']:last-of-type": "accepted"
  }
});

// async/await
const state = await validatinator.validate(".my-form-query-selector");
console.log(state.valid); // or state.invalid
console.log(state.getAllErrors()); // or state.getFieldErrors(".another-field")

// or as a promise
validatinator.validate(".my-form-query-selector").then((state) => {});

Why does this exist?

Validatinator originally existed through the want of giving to the development community. As of 2022, this project is >6 years old, and has been stagnant for the majority of that time.

While the library may have been stagnant, it has been poised to do well due to the fact that it "just works". Along with all of the technological advancements we've underwent in the past 6 years; now the core pillars of Validatinator's existence are locked to:

  • Zero dependencies
  • Ease of use
  • Framework & runtime agnostic (soon)
  • Configurable and override-able

The holy grail of ease-of-use JS/TS validation libraries.

Validation Methods

  • "accepted"
  • "alpha"
  • "alphaDash"
  • "alphaNum"
  • "alphaDashNum"
  • "between:2,10"
  • "betweenLength:2,10"
  • "contains:2,4,6,8,10,12"
  • "dateBefore:2022-02-04"
  • "dateAfter:2022-02-10"
  • "difference:.my-other-field-selector,false"
  • "digitsLength:3"
  • "digitsLengthBetween:3,10"
  • "email"
  • "ipvFour"
  • "max:500"
  • "maxLength:2"
  • "min:200"
  • "minLength:2"
  • "notIn:2,4,6,8,10,12"
  • "number"
  • "pattern:valid_regex_string"
  • "required"
  • "requiredIf:.another-field-selector,value-to-check"
  • "requiredIfNot:.another-field-selector,value-to-check"
  • "same:.another-field-selector,false"
  • "url"

Validation Method Notes

  • difference - The second argument is strict which when false performs case insensitive comparisons.
  • same - The second argument is strict which when false performs case insensitive comparisons.
  • pattern - The valid regex string will be compared against the field value and if any part of the value matches the string, it will be valid. To strictly match the field value one must include the "starts with" (^) and "ends with" ($) assertion characters. A backslash inside the regex string must be escaped to be processed as a literal backslash (ex: "pattern:\\d" to match any numeric digit).

validatinator's People

Contributors

jenkinsdev avatar lynxnathan avatar mpriour avatar robert8888 avatar ryanwarner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

validatinator's Issues

Email validation

This email foo@foo,com is valid, but it should be. Because the email contain a comma.

Checkbox not working with requiredIf

Great plugin by the way!

I have a checkbox and a hidden field set to either true or false.

The checkbox should only be validated against if the hidden field is set to 'true'. I am using requireIf, but this doesn't appear to be working. The form passes the validation whether it's checked or not.

Rules:

  const validator = new window.Validatinator({
    'my-form': {
      'terms': 'requiredIf:payment_required:true'
    }
  });

HTML:

<form name="my-form">
  <input name="payment_required" type="hidden" value="true">
  <input name="terms" type="checkbox" value="mycheckbox" id="terms">
</form>

Is this a known issue? I cannot find much information on validating checkboxes against another field.

Thanks.

UPDATE:

I think this related to changing the 'payment_required' field's value dynamically with JavaScript. It doesn't seem to get picked up from a value that's changed this way.

Enhance core files with ES6

ES6 support was added with the introduction of browserify with the babelify transform. Let's make use of babel!

  • Less Var - More Let
  • Classes > Prototypes
  • Arrow Function > function() {} [In most cases]
  • ....

Validation with input name attributes may colide

Hey,

Im using validatinator on one of my projects. Anyway, I've run into an issue, that if your input name attribute colide with e.g. meta tag, the validatinator gets broken, because it checks in getFieldsValue() method whether the input name exists, but not within the form, but inside document.

So if you have <meta name="author" value="xx" /> and inside a document you have <input name="author" ...> the method fails.

The method should check whether it is really inside the form, not in document.

Validations which reference another field do not work when prepared from a config

This issue effects:

  • same
  • difference
  • requiredIf
  • requiredIfNot

In all of these methods the otherField parameter is expected to be an HTMLInputElement. However, when the validation method is prepared from a string via the config, this parameter is a string. For example:

{
  ".my-form": {
    ".my-field-selector": "required|same:.other-field-selector",
   }
}
/* is parsed to */
[
   ["required"],
   ["same", ".other-field-selector"]
]

/* Then the validation is called like this */
HTMLFormValidations.same(form, field, ".other-field-selector")

/* Within the "same" method this becomes */
...
field.value == ".other-field-selector".value
...

/* This always evaluates to false since strings do not have a "value" property */

Similar issues are present in the other methods.

I'm happy to provide a PR which will address these issues.

Data attributes

(not an issue, merely a question) Is it possible to initiate the form validation based on data attributes?
eg:
<input type="text" name="my-fields-name-attribute" data-required="true">

ALPHA_REGEX should have * quantifiers not +

Why Alpha and others validators

const ALPHA_REGEX = new RegExp(/^[a-zA-Z]+$/);
const ALPHA_DASH_REGEX = new RegExp(/^[a-zA-Z-_]+$/);
const ALPHA_NUMERIC_REGEX = new RegExp(/^[a-zA-Z0-9]+$/);

have "+" what means that they expect not only Alpha character but it "REQUIRE" at least one char. What means that they force people to put something there.

It should be write like that :

new RegExp(/^[a-zA-Z]*$/);

And if some one need alpha and required then he have to combine validators: 'required|alhpa'

6 years projects and still .....

Release 2.0.4 is missing types

The types declarations are missing from the dist directory in the npm release.
Not sure if something went wrong for the 2.0.4 release or if this is a more long standing problem but there is no ./dist/types directory included when installing from npm.

Cannot run Validatinator correctly on 2+ forms with the same name

At first glance, having multiple forms with the same names (and the same fields and validation rules) appears to work...but after an initial validation run, it's impossible to correct / re-validate the form again - I assume because it's getting stuck on another form of the same name.

The reason I have multiple forms is that this website in particular repeats the same newsletter signup form throughout a very long page and it's placed there via multiple includes.

It would be very repetitive to have to maintain forms as being distinct, even if they're the same with just a different name simply because validation wont run on multiple forms of the same name.

Any ideas with this at all? It's a bit of a road blocker for me. As far as I know Validatinator only works with names.

Add per field custom validation messages

Hey. It'd be really handy to be able to specify custom validation messages for different fields

var validator = new Validatinator({
    signUpForm: {
        name: 'required',
        email: 'required'
    }
}, {
    signUpForm: {
        name: {
            required: 'Please provide a name.'
        },
        email: {
            required: 'You really should have email.'
        }
    }
});

Thanks for the awesome work

Add custom regex pattern matching

While this library has lots of good validation options, some valid field values simply don't fit neatly into one of those validation options. It would be nice to have a way to pass a RegEx string as part of a field validation configuration.
For example:

{
   ".my-field-query-selector": "required|pattern:\\d{3}[\\*_\\-][a-z]{4}",
   ...
}

This example would create a regular expression for a field value that starts with 3 numbers has one of *, _ , - and is followed by 4 lowercase letters.

Then this could be parsed in a new pattern method:

static pattern(form: HTMLFormElement, field: HTMLInputElement, regexPattern: string) {
  const regex = new RegExp(regexPattern);  
  return regex.test(field.value);
}

The double backslash is required since it is in a string. A single backslash would only create an escape sequence inside the string and would not result in a literal backslash in the constructed regular expression.

validation fails with exception when an input field is named "name"

getFieldsValue will raise an exeption if e.g. a hidden field is named "name" and one field to be validated

this

163: if (fieldElement.form && fieldElement.form.name === form) {

will be false, because fieldElement.form.name will return the input "<input type=​"hidden" name=​"name" value>​"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.