2

In my laravel project i have written an custom form validation class. after compiling with npm run dev i dont have access to this class.

My files

small-form-validation.js

class SmallFormValidator {
    errMsgs = {
        required: 'This field is required!',
        string: 'Not valid string.',
        ...

my app.js

require('./bootstrap');
require('./myvendor/small-form-validator');

After compiling i found in the new created app.js file inside the public folder the source from class SmallFormValidator. It seems that he compiled right.

in my blade template i load with the mixing helper the app.js file. in my Javscript inside the blade template i cant create a instance of SmallFormValidation (var sfv = new SmallFormValidation() ).

I think the problems result that

  1. I dont work with module export and so on
  2. or i have some scope problems.

Does anyone know how to solve the problem?

1 Answer 1

2

an easy fix would be to assign it to your global/window object. in small-form-validation.js add window.SmallFormValidator = SmallFormValidator to make it globally accessible.

A better way would be to use module exports and imports

Example

//add this add the end of the file
export default SmallFormValidator

// or to the line where you start declaring the class like so:
export default class SmallFormValidator {
  // class stuff
}

in the file where you want to use it you can import it like this:

// top of your file
import SmallFormValidator from '../path/to/small-form-validation'

// use it how ever you want in this file
const smallFormValidator = new SmallFormValidator()
smallFormValidator.jeKaleZus() // or any other method you have

Hope this helps

Sign up to request clarification or add additional context in comments.

2 Comments

Can you Explain the way with modules please?
It's a while ago but I updated my answer. May still be useful to select it as the accepted answer to help others out who have same question you had

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.