Giter Club home page Giter Club logo

pristine's Introduction

Pristine - Vanilla javascript form validation library

{:.hide}

~4kb minified, ~2kb gzipped, no dependencies

Living demo

Some examples of use can be found here.

Usage

Include the javascript file in your html head or just before the closing body tag

<script src="dist/pristine.js"  type="text/javascript"></script>

Now create some form and validate

window.onload = function () {

    var form = document.getElementById("form1");

    // create the pristine instance
    var pristine = new Pristine(form);

    form.addEventListener('submit', function (e) {
       e.preventDefault();
       
       // check if the form is valid
       var valid = pristine.validate(); // returns true or false

    });
};

That's it

It automatically validates required, min, max, minlength, maxlength attributes and the value of type attributes like email, number and more..

Pristine takes 3 parameters

  • form The form element

  • config An object containing the configuration. Default is bootstrap's configuration which is

let defaultConfig = {
    // class of the parent element where the error/success class is added
    classTo: 'form-group',
    errorClass: 'has-danger',
    successClass: 'has-success',
    // class of the parent element where error text element is appended
    errorTextParent: 'form-group',
    // type of element to create for the error text
    errorTextTag: 'div',
    // class of the error text element
    errorTextClass: 'text-help' 
};
  • live A boolean value indicating whether pristine should validate as you type, default is true

Install

$ npm install pristinejs --save

Custom Validator

pristine.addValidator(nameOrElem, handler, errorMessage, priority, halt);

Add a custom validator to a field

var pristine = new Pristine(document.getElementById("form1"));

var elem = document.getElementById("email");

// A validator to check if the first letter is capitalized
pristine.addValidator(elem, function(value) {
    // here `this` refers to the respective input element
    if (value.length && value[0] === value[0].toUpperCase()){
        return true;
    }
    return false;
}, "The first character must be capitalized", 2, false);

Add a global custom validator

// A validator to check if the input value is within a specified range
// Global validators must be added before creating the pristine instance

Pristine.addValidator("my-range", function(value, param1, param2) {
    // here `this` refers to the respective input element
    return parseInt(param1) <= value && value <= parseInt(param2)
    
}, "The value (${0}) must be between ${1} and ${2}", 5, false);

Now you can assign it to your inputs like this

<input type="text" class="form-control" data-pristine-my-range="10,30" />

Add custom error messages

<input required data-pristine-required-message="My custom message"/>

Add an attribute like data-pristine-<ValidatorName>-messagewith the custom message as value to show custom error messages. You can add custom messages like this for as many validators as you need. Here ValidatorName means required, email, min, max etc.

Built-in validators

Name Usage Description
required required or data-pristine-required Validates required fields
email type="email" or data-pristine-type="email" Validates email
number type="number" or data-pristine-type="number"
integer data-pristine-type="integer"
minlength minlength="10" or data-pristine-minlength="10"
maxlength maxlength="10" or data-pristine-maxlength="10"
min min="20" or data-pristine-min="20"
max max="100" or data-pristine-max="100"
pattern pattern="/[a-z]+$/i" or data-pristine-pattern="/[a-z]+$/i", \ must be escaped (replace with \\)
equals data-pristine-equals="#field-selector" Check that two fields are equal

API

Pristine(form, config, live)
Constructor

Parameter Default Required? Description
form - The form element
config See above The config object
live true Whether pristine should validate as you type

pristine.validate(inputs, silent)
Validate the form or field(s)

Parameter Default Required? Description
inputs - When not given, full form is validated. inputs can be one DOM element or a collection of DOM elements returned by document.getElement..., document.querySelector... or even jquery dom
silent false Does not show error messages when silent is true

pristine.addValidator(elem, fn, msg, priority, halt)
Add a custom validator

Parameter Default Required? Description
elem - The dom element where validator is applied to.
fn - The function that validates the field. Value of the input field gets passed as the first parameter, and the attribute value (split using comma) as the subsequent parameters. For example, for <input data-pristine-my-validator="10,20,dhaka" value="myValue"/>, validator function get called like fn("myValue", 10, 20, "dhaka"). Inside the function this refers to the input element
message - The message to show when the validation fails. It supports simple templating. ${0} for the input's value, ${1} and so on are for the attribute values. For the above example, ${0} will get replaced by myValue, ${1} by 10, ${2} by 20, ${3} by dhaka. It can also be a function which should return the error string. The values and inputs are available as function arguments
priority 1 Priority of the validator function. The higher the value, the earlier it gets called when there are multiple validators on one field.
halt false Whether to halt validation on the current field after this validation. When true after validating the current validator, rest of the validators are ignored on the current field.

Pristine.addValidator(name, fn, msg, priority, halt)
Add a global custom validator

Parameter Default Required? Description
name - A string, the name of the validator, you can then use data-pristine-<NAME> attribute in form fields to apply this validator
.... - - Other parameters same as above

pristine.getErrors(input)
Get the errors of the form or a specific field

Parameter Default Required? Description
input - When input is given, it returns the errors of that input element, otherwise returns all errors of the form as an object, using input element as key and corresponding errors as value. validate() must be called before expecting this method to return correctly.

pristine.addError(input, error)
Add A custom error to an input element

Parameter Default Required? Description
input - The input element to which the error should be given
error - The error string

pristine.setGlobalConfig(config)
Set the global configuration

Parameter Default Required? Description
config - Set the default configuration globally to use in all forms.

Pristine.setLocale(locale)
Set the current locale globally

Parameter Default Required? Description
locale - Error messages on new Pristine forms will be displayed according to this locale

Pristine.addMessages(locale, messages)
Set the current locale globally

Parameter Default Required? Description
locale - The corresponding locale
messages - Object containing validator names as keys and error texts as values

pristine.reset()
Reset the errors in the form


pristine.destroy()
Destroy the pristine object



The goal of this library is not to provide every possible type of validation and thus becoming a bloat. The goal is to provide most common types of validations and a neat way to add custom validators.

License

MIT

pristine's People

Contributors

cruzr1 avatar dimagashko avatar dlueth avatar enriqueprieto avatar karl33to avatar luca-vercelli avatar muhroots avatar pfuhrmann avatar psmyrdek avatar sha256 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  avatar  avatar  avatar

pristine's Issues

Code in NPM registry is not latest

The js that is downloaded via npm install does not match the latest in the repo... can this please be fixed? The 'equals' and the 'pattern' both have issues in the version in the registry but they work great on the demos using the most current code. Our project relies on the registry as part of the build process for 3rd party code. Thanks in advance!

Master branch does not match npm tag code.

Hello!

The code downloaded when installing via npm does not to match the code in the master branch. It lacks the setLocale and addMessages methods on the Pristine constructor. Looks like there was no new tag (I guess it should be 0.2.0) created for this feature and published to npm.

Would it be possible to update this?

Thank you for maintaining this library!

errorClass not work with textarea

Hi!

Add to form Pristine and add my defaultConfig:

defaultConfig = {
       classTo: 'uk-form-controls',
       errorClass: 'uk-form-danger',
       successClass: 'uk-form-success',
       errorTextParent: 'uk-form-controls',
       errorTextClass: 'uk-text-small'
}

With input tag Pristine working fine, but not correct working with textarea -- border teaxtarea tag not apply errorClas

Update validation with select library

Hello,

I’m trying to figure out if there’s some sort of settings I need to update if I’m using a library for select box to make sure validation is remove if it passed the criteria. Is there ? Pristine validates when the value of select is empty but when I go go to select a value it doesn’t update as pass.

I am using choices js https://github.com/jshjohnson/Choices

Thank you!!

demo page broken

the only demo page working is Common validations, the others just give you a blank screen.

Can't get to work addError()

const a = form.querySelector('input[name="email"]'); pristine.addError(a, 'asd');

It gives me:

Uncaught TypeError: Cannot read property 'push' of undefined
at f.addError (pristine.min.js:1)

How should i use addError()?

Thanks!

Doesn't validate the data-pristine-equals.

<input type="password" id="pwd" required data-pristine-required-message="Please Enter a password" 
data-pristine-pattern="/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$/" 
data-pristine-pattern-message="Minimum 8 characters, at least one uppercase letter, one lowercase letter and one number" class="form-control" />
  
<input type="password" data-pristine-equals="#pwd" data-pristine-equals-message="Passwords don't match" class="form-control" />

window.onload = function() {
        // pristinejs validation
        var form = document.getElementById("pristine-valid-example");
        var pristine = new Pristine(form);
        form.addEventListener('submit', function(e) {
            var valid = pristine.validate();
            // alert('Form is valid: ' + valid);
            if (valid) {
                return true;
            } else {
                e.preventDefault();
            }
        });
  }

Doesn't validate the data-pristine-equals

Avoid to validate fields that has not validation

When you have input that has not validation, for example an input checkbox "Remember me", right now it make it valid and hightlight in green when you do validation, example:

Screenshot 2020-10-14 at 08 55 17

Why not just skip this fields that has not any validation found?

This could be easy done in init() function adding a check if fns is empty, example:

            if(fns.length) return input.pristine = {input, validators: fns, params, messages, self};

What do you think?

Accessibitity

If you implement e11y it's will be so useful.

(or at least events like 'onvalid', 'oninvalid')

update build files

Hi,

may u update the build files in this repo please 😘? (or keep src and dist folders synced)

ty!

Add error after ajax submissions

After form validation passed, I am making an ajax form submission, and then catch errors from server which make additional validation.

I have used before with custom JS to append errors but this are not removed by pristine, so I see method addError and this correctly mark input invalid, but don't show error message.

Am I missing something? Should addError also append error message?

This is my code:

  axios({
            method: method,
            url: url,
            data: data
        })
            .then(function (response) {
               // success here removed
            })
            .catch(function (error) {

                   // Part of code that matters here
                        let errors = error.response.data.errors
                        for (let input in errors) {
                            if (errors.hasOwnProperty(input)) {
                                // Avoid to show message if already exist
                                if (!form.querySelector('.invalid-feedback-' + input)) {

                                    // Add error using pristine
                                    pristine.addError(form.querySelector('[name="'+input+'"]'), errors[input][0])

                                    // I used below code to append invalid feedback:

                                    // let invalidFeedback = document.createElement("div");
                                    // invalidFeedback.classList.add('invalid-feedback', 'invalid-feedback-' + input)
                                    // invalidFeedback.style.display = 'block'
                                    // invalidFeedback.innerHTML = errors[input][0]
                                    // let inputElement = form.querySelector('[name="'+input+'"]')
                                    // inputElement.classList.add('is-invalid')
                                    // if(inputElement) {
                                    //     inputElement.parentNode.insertBefore(invalidFeedback, inputElement.nextSibling)
                                    // }
                                }
                            }
                        }
            })

Thanks

Improve documentation

I spent a lot of time creating custom validators, later realizing that the same results could already be achieved with the standard validators.
I have written some more realistic examples here:
https://codepen.io/luca-vercelli/full/KKzMJvR

(please notice that the Pen points to the CDN https://combinatronics.com/Sha256/Pristine/master/dist/pristine.js )

I think the http://pristine.js.org/demo.html page could be reorganized that way:

  1. Common validations
  2. Real-world examples (@sha256 this could point to my Pen, or you could create a similar one)
  3. Custom validator to a specific field
  4. Custom global validator

and the example "Custom error messages" can be omitted.

Second issue, I think that the "Demo" link in README.md file should not be in a title, it took me a while to realize it was a link.

Third issue, the "API" section of the README.md file could be moved in a separate file.

If you agree, I could work on this.

Validating the number of characters

I want to add password validation, but code from the example https://pristine.js.org/demo.html gives the error

Uncaught TypeError: Cannot read property '1' of null

From #10 (comment) i found out that the reason is in the comma. RegEx "/^(?=.?[A-Z])(?=.?[a-z])(?=.*?[0-9]).{8,}$/" contains commas. But in the example everything works, what can be done to make the pattern work?

Custom Validator with Promise / XHR Requests ("Timeouts") are not working / always false

Hej,

i try to check the input against an API / XHR Request and output the error according to the response as true or false.

I’ve tried it with a simple Timeout within one of the demos:
https://codepen.io/Maybach/pen/mdEQjWN

When you remove the setTimeout on line 12, then it works. The timeout simulates my XHR request (which takes time / is a Promise).

What i’m trying to do:
Only when the input is valid (an e-mail), then send the XHR request. XHR Request response with a 200 or 409. If 200, the input is valid / free username. If 409 the e-mail is already registered and want to tell this the user.

pristine.addValidator(
    emailField,
    function (value) {
      if (!this.validity.typeMismatch) { // Check if HTML5 says its a valid input → maybe do this with Pristine as well
        makeRequest({
          method: "GET",
          url:
            "REQUESTURL?username=" +
            value
        })
          .then(function (data) {
            return true;
          })
          .catch(function (err) {
            console.log(err);
            return false;
          });
      }
      return false;
    },
    "E-Mail already registered, want to Login?",
    2,
    true
  );

(makeRequest is just a simple XHR Request which returns a Promise → this works)

Email validator does not check for valid characters

I have found that Pristine's built-in email validation rules only check for a structurally correct email address (e.g. [email protected]) but does not check for invalid characters in the username part. For example, in 99% of cases a comma is not allowed in an email address but Pristine does not raise an error when it encounters one.

A good reference for what can and cannot be included in an email address is detailed here.

Skipping fields without validators

I have a form that is split into several steps. When the user clicks a button to progress to the next step, I would like to validate all the fields on the current tab.

I thought I might be able to pass a selector for the step's div which contains multiple fields, but it seems I have to pass in the actual form elements (e.g. input, select).

So I thought I'd go through the form's elements, but I get this error when it hits a FormElement that doesn't have a validator. For example, a fieldset which contains other inputs.

Uncaught TypeError: Cannot read property 'validators' of undefined

Is there a way to skip validation for for things that are passed into validate() that don't have validators? Or is there a smarter way to achieve what I'm trying to do? Thanks!

Possible to globally set default messages for built-in validators?

Is it be possible to programmatically define a default message for one of the built-in validators, such as required? That is, rather than defaulting to This field is required, can that string be set globally, perhaps at initiation, to something else? (I know that I can do this though data-attributes, but adding a data-attribute to every input becomes tedious pretty quickly, and I'm not seeing an alternative in the docs.)

If this is not already possible, perhaps the config object passed to new Pristine() could also take an object of messages, with keys there defining each of the built-in validators' default messages?

let defaultConfig = {
    classTo: 'form-group',
    errorClass: 'has-danger',
    successClass: 'has-success',
    errorTextParent: 'form-group',
    errorTextTag: 'div',
    errorTextClass: 'text-help',
    messages: {
        required: '🙅  This field is required!',
        email: 'Give us your email!',
       {...}
    }
};

valid always return true!

I just copy the code and replace the form id with my form id. But the valid variable always returns true. It's doesn't return any error or anything.

// pristine validation
window.onload = function () {
var form = document.getElementById("sign-in");

// create the pristine instance
var pristine = new Pristine(form);

form.addEventListener("submit", function (e) {
    e.preventDefault();

    // check if the form is valid
    var valid = pristine.validate(); // returns true or false
    console.log(valid);
    console.log(pristine);
});

};

Password match validation?

Hello,

How could add password matching. I'm trying to use addValidator but this functin only has to parameters. So I don't know the correct way to validate those fields.

Thank you!

isFunction helper

Why do you use this helper?

export function isFunction(obj) {
    return !!(obj && obj.constructor && obj.call && obj.apply);
}

Why not just typeof func === 'function'?

HTML5 vs Pristine RegEx patterns

From the README, it seems that Pristine requires the use of / to contain the RegEx pattern:

pattern="/[a-z]+$/i" or data-pristine-pattern="/[a-z]+$/i"

When these delimiters are added in the pattern attribute, HTML5 validation doesn't work as a fallback [example].

When I tried adding both pattern with the HTML5 RegEx format and data-pristine-pattern with a JS RegEx format to the same input, the error message was duplicated.

Support for ES6?

Any plans (or willing to take a PR for ES6 Import support so it's easier to use with compiled projects?

Reset deletes elements

The reset function (as well as the destroy function since it calls reset) actually deletes the elements from the dom. I do not believe this should be the intended behavior of a reset. I would expect it to simply remove the error and success statuses and reset the pristine instance to the state it was at before the form was validated. Am I thinking about this incorrectly?

This is the bit of code that removes the elements

Array.from(self.form.querySelectorAll('.' + PRISTINE_ERROR)).map(function (elem) {
    elem.parentNode.removeChild(elem);
});

Functionnality to use var into a addValidator for the error message

Hi Sha,

First, thanks for your library, it's pretty cool and easy to use.

I'm currently looking to add custom message error into an "addValidator", but when i try to use it, i cant get my var out of the scope (pwdError).

var password = form.querySelector('.passwordValidate');
var regEx = {
    char : new RegExp("^(?=.{8,})"),
    maj : new RegExp("^(?=.*[A-Z])"),
    min : new RegExp("^(?=.*[a-z])"),
    num : new RegExp("^(?=.*[0-9])"),
    spe : new RegExp("^(?=.*[!@#\$%\^&\*])")
}
var pwdText = {
    char : '8 caractères',
    maj : '1 majuscule',
    min : '1 minuscule',
    num : '1 chiffre',
    spe : 'un caractère spécial'        
}

if(password) {
    let pwdError = '';
    let regex = function (password) {

        pwdError = '';
        Object.keys(regEx).forEach((key) => {
            if(!regEx[key].test(password.value) && pwdError.replace((pwdText[key]), '') === pwdError ) {
                pwdError = pwdError + ', ' + pwdText[key];
            }
            else {
                return true;
            }
        })

        if(pwdError == '') {
            pwdError = '';
        }
        else {
            pwdError = 'Votre mot de passe doit contenir au minimum' + pwdError + '.';
        }
        console.log(pwdError)
        return false;
    }
    pristine.addValidator(password, function() {
        regex(password);
    }, 'pwdError', 2, true);
}

pwdError is null but the console.log is full.

Don't have any functionality to change the default error messages

Hey there,

Nice library you have here, but I'm just wondering if there's any plan on adding the ability to customise the error message text for the default validations, e.g. required gives the error "This field is required".

Seems that I have to do a silent validation add my own errors.

On a side note, on your Demos page, only 1 demo works, the rest are blank HTML files.

Can't get errors to show

I'm trying to implement Pristine, but I can't figure out the HTML to add to get the errors to show.

I currently have this:

            <div class="form-group">
                <div class="has-danger has-success"></div>
            </div>

But no errors show up there.

validate() silent option is ignored / not working

I’m trying to valid a specific input field as silent. According to the documentation it should be simple like pristine.validate(input, true);. But its ignored.

Look at line 25:
https://codepen.io/Maybach/pen/mdEQjWN

   // Silent is ignored
   pristine.validate(elem, true);
   pristine.addError(elem, "Testerror Message");

Expected:
Shows only "Testerror Message" on page load.

Also is it intended that i have to validate the input first to add my custom error?
I’m trying to get a workaround for #51 where i request the API without the addValidators function.

TS Types for autocomplete

Can you add Pristine to http://definitelytyped.org/ (or just add jsdoc comments) ?

Because there's no intellisense for Pristine instance now.
You know, I mean:

image

Screenshot from 2019-12-18 15-57-32

Yea, it's not so important, but I think it's definitely adds some points to any library. And intellisense increase usability of a lib

License

Would you please add license to the library? I am considering using it for a commercial project and without the license I am not able to do so. Thanks

Pristine need events triggers

It would be great if there are events that are fired when the fields or the form have been validated without the need to call the valid() method.

Bootstrap 4 and Bootstrap 5 validation

I would like to use bootstrap 4 and bootstrap 5 default validation classes, but seem not possible.

For display .invalid-feedback the input must have .is-invalid or .valid-feedback with .is-valid, example:

<div class="form-group">
      <input type="text" class="form-control is-invalid" required="">
      <div class="invalid-feedback">This field is required</div>
</div>

<div class="form-group">
      <input type="text" class="form-control is-valid" required="">
      <div class="valid-feedback">Looks good</div>
</div>

If I change the default class name like so:

    let validator = new Pristine(form, {
        classTo: 'form-group',
        errorClass: 'is-invalid',
        successClass: 'is-valid',
        errorTextParent: 'form-group',
        errorTextTag: 'div',
        errorTextClass: 'invalid-feedback'
    })

The errors is not visible because class .is-invalid is not added to input but to form-group, example:

<div class="form-group is-invalid">
            <label for="email">E-Mail Address</label>
            <input type="email" id="email" name="email" class="form-control" required="">
            <div class="pristine-error invalid-feedback">This field is required</div>
</div>

I could solve this by adding extra CSS like .is-invalid .invalid-feedback {display: block} (not completely because need also to consider input group border, dark theme of bootstrap 5, etc). Would be good to have a way to do this without extra CSS, if possible without breaking change.

Bootstrap has also a class .was-validated, that show invalid feedback depending on HTML5 validation, like .was-validated :invalid ~ .invalid-feedback {display: block}

But this doesn't work for example with input type email where HTML5 consider valid email@example while pristine correctly mark this as invalid.

Pristine block request

Pristine block the request of my form

<form id="form1" name="form" class="box" action="" method="post">
  <h1>Créer un compte</h1>

  <div class="form-group">
  <input type="text" name="username" id="username" placeholder="Nom d'utilisateur" required data-pristine-required-message="*Ce champ est requis" required>
  </div>
  <div class="form-group">
  <input type="text" name="email" placeholder="Email" data-pristine-type="email" required>
</div>
  <div class="form-group">
  <input type="text" name="firstname" placeholder="Prenom" required>
</div>
  <div class="form-group">
  <input type="text" name="lastname" placeholder="Nom" required>
</div>
  <div class="form-group">
  <input type="password" name="password" placeholder="Mot de passe" required>
</div>
<div class="form-group">
  <button type="submit" name="submit" value="Créer l'utilisateur">
</div>
<div class="form-group"></div>
  <div class="g-recaptcha" data-sitekey="--------------------------"></div>
</div>
</form>
window.onload = function () {

    var form = document.getElementById("form1");
 
    var pristine = new Pristine(form);
 
    form.addEventListener('submit', function (e) {
       e.preventDefault();
       var valid = pristine.validate(); 
 
    });
 
 
 };

Can't access element in custom validator

If I do something like this, I get undefined as for this. Is there a way to access the element?

Pristine.addValidator(
  "choices",
  (value) => {
    console.log(this);
    return false;
  },
  "This field is required"
);

Issue faced with adding a global validator

Codepen
https://codepen.io/xavianaxw/pen/EGeWLj

Description
I've tried setting up PristineJS with a custom global validator my-range that throws an error when the value input is not between the minimum and maximum value. This was as per the example on the README.

In my HTML, I've set the input to respect the required and data-pristin-my-range="10,30" rule.

Expected behavior

  1. Input throws an error on required
  2. Input throws an error on data-pristine-my-range if not between 10 - 30

Outcome

  1. Input does throw an error on required
  2. Input does not respect data-pristine-my-range rule set.

Would be best if you can help point me in the right direction!

Cheers

ability to add defaults to custom validator message

I have set up a zip code validator with a custom validation error message. I would like to be able to have a default validation error message in case a custom message is not used.

Currently the element looks like this:
<input type="text" data-pristine-required-message="The zip code field is required" data-pristine-zip-code="true,Please enter a valid US zip code" required>

And in the JS code:

Pristine.addValidator('zip-code', function (value, mode) {
    let pattern;
    // see if we are just checking for 5 digit zip
    if (mode == 'strict') pattern = /^[0-9]{5}?$/;
    // otherwise zip+4
    else pattern = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
    return pattern.test(value);
}, '${2}', 5, false);

This works. But I would also like to support instances where the element does not pass the error message as a second parameter:
<input type="text" data-pristine-required-message="The zip code field is required" data-pristine-zip-code="true" required>

The code would fill in a default value. Something that works like a template literal:

Pristine.addValidator('zip-code', function (value, mode) {
    let pattern;
    // see if we are just checking for 5 digit zip
    if (mode == 'strict') pattern = /^[0-9]{5}?$/;
    // otherwise zip+4
    else pattern = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
    return pattern.test(value);
}, "${2 || 'Please enter a valid US zip code'}", 5, false);

This does not work. Is there a method for doing this within the current code?

feature request: blur event + localization

I've an autocomplete attached to an input and i've added a custom validator too.
In such situation validating the field on the "blur" event would be nice to have.

Is there a reason why this is not done automatically or implemented?

Can it be added?

It would be also nice to have a way to customize some of the lang string through global var or option parameter.

Thank you :)

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.