Don't know where to look?

You can search all my notes here

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.

sh
yarn add jquery parsleyjs
main.ts
typescript
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
    • jquery

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:

package.json
json
{
  "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:

main.ts
typescript
$.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)

main.ts
typescript
import 'parsleyjs/src/i18n/de'
window.Parsley.setLocale(
  document.documentElement.getAttribute('lang') || 'en'
)

Comments

Post-Meta
  • Published: April 15, 2020
  • Last modified: April 20, 2020
Included files
  • main.ts
  • package.json
  • readme.md
Download all