Using parsley.js with yarn
Parsley.js is a very helpful library to help you validate forms in the frontend.
To use this library with a package-manager, you can import the library using the following code.
yarn add jquery parsleyjs
import $ from 'jquery'
import 'parsleyjs'
window.jQuery = $
window.$ = $
When you do this and then type $.fn.parsley
into the Javascript-console in the developer tools, it will tell you that this function is undefined. That’s because parsleyjs installs it’s own version of jQuery and loads that instead of using your project’s jQuery.
Your folder-structure will look something like the following:
- node_modules
- parsleyjs
- node_modules
- jquery
- node_modules
- jquery
- parsleyjs
That’s because parsley lists "jquery": ">=1.8.0"
as one of it’s dependencies and yarn will then install a seperate copy of jQuery 1.8.0 because you will most probably use the latest version of jQuery.
To prevent yarn from doing that, you can fix the jQuery-Version for your package and all subpackages using the following code:
{
"resolutions": {
"jquery": "3.4.1"
}
}
If you use this code in the future, make sure to change the jQuery-Version to the latest one.
Adding defaults
To change the default parsley-settings for all instances use the following code:
$.extend(window.Parsley.options, {
// Default options for bootstrap 4 with bootstrap-select
classHandler({ $element }) {
if (
$element.is('select') &&
$element.parent().is('.bootstrap-select')
) {
return $element.parent()
}
return $element
},
errorsContainer({ $element }) {
return $element.closest('.form-group, .form-check')
},
errorClass: 'is-invalid',
errorsWrapper: '<div class="invalid-feedback"></div>',
errorTemplate: '<span></span>',
successClass: 'is-valid',
trigger: 'blur change ',
triggerAfterFailure: 'input change',
})
For a list of all available options see: https://parsleyjs.org/doc/annotated-source/defaults.html
Localizing parsley
To localize parsley import all required translations (except en)
import 'parsleyjs/src/i18n/de'
window.Parsley.setLocale(
document.documentElement.getAttribute('lang') || 'en'
)
- Published: April 15, 2020
- Last modified: April 20, 2020
Comments