sha256 / pristine Goto Github PK
View Code? Open in Web Editor NEWVanilla javascript form validation micro-library
Home Page: https://pristine.js.org/
License: MIT License
Vanilla javascript form validation micro-library
Home Page: https://pristine.js.org/
License: MIT License
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
<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
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?
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.
When adding or removing the required attribute it seems that pristine does not detect the change.
Wich is the correct way to tell pristine that the dom has changed?
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?
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.
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:
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?
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.
When I put min="9" in a field, as soon as I type two characters the input is already green as if it was correctly validated, the same happens with max
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)
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!
Hi, how can I prevent whitespace on input required?
https://stackoverflow.com/questions/13766015/is-it-possible-to-configure-a-required-field-to-ignore-white-space
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!',
{...}
}
};
the only demo page working is Common validations, the others just give you a blank screen.
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
required
data-pristine-my-range
if not between 10 - 30Outcome
required
data-pristine-my-range
rule set.Would be best if you can help point me in the right direction!
Cheers
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();
});
};
This will help us know if we have the latest version. Right now there is nothing that tells us what version we are using.
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!!
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 :)
Hi @sha256
Since version 1.0.0, All errors messages are properly injected except for the required one.
Can you check please ?
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.
Why do you use this helper?
export function isFunction(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
}
Why not just typeof func === 'function'
?
Works with the version included in the codepen. Tried that version locally and works fine. But with the version installed through npm "pristinejs": "^0.1.9"
doesn't work.
The message templating style (example) is very similar to template literals native to JavaScript, but it isn't.
This confuses ESLint, and is also confusing for developers.
It would be great if the message template used JS template literals.
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!
I have dependent fields in the form. How to ignore hidden fields from validation.
if you input "111AAA333" or "123456d" on field "number" or "integer" does not return error.
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!
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:
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
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);
});
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"
);
Hi,
may u update the build files in this repo please 😘? (or keep src and dist folders synced)
ty!
If you implement e11y it's will be so useful.
(or at least events like 'onvalid', 'oninvalid')
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!
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.
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.
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.
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.
Any plans (or willing to take a PR for ES6 Import support so it's easier to use with compiled projects?
This would be nice to be able to localize, or change, default errors message.
Maybe though the defaultConfig parameter ?
Thanks.
Hi, it could be good to implement the native scrollIntoView() function on every input field if pristine return false. I make a PR for that
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
Example: https://jsfiddle.net/n9jcwukp/
This error shows in the console when you type in the 2nd input which has a comma in the pattern:
Uncaught TypeError: Cannot read property '1' of null
It may have something to do with this line, which splits all parameters at commas.
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
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!
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:
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.
Hi does anyone have a custom validation they can share for checking valid url? Appreciate any help
I saw this https://rubular.com/r/eGPe4bGlwMd98E but couldn't get the regex working
Or did I do something wrong?
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);
});
};
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.