Use external js file or controller?

I want to create a class just to call in other controller.
Now which is better?
1 - create a extra folder (like js) and create a .js file and call it on each controller that I want
2 - create a controller and call it on each controller that I want

It is very hard to give some guidance without seeing your code and getting a clearer understanding of what you want to do.

It would be good to also understand your setup, have you got a Node build tool environment running or are you using ESM (ES Modules). Showing your code will help answer that.

As a bit of general advice:

  • Read the docs in full, twice, then see if you have an answer to your question (for example - there is a section on how to get two controllers to talk to each other - Stimulus Reference ).
  • When learning; you first just need to get it working any way you can, then commit the changes to git so you know it is working. After that you can think about how to rework it to be ‘better’, taking a moment to review what you have done.
  • Do not worry about folder structure too early, you can always move things around later as needed.
1 Like

@lbee Thank you.
I want to create a validation form and use that in each form that I want.
It has many functions like ( if empty then) (if equal then) (if max than x then) and …
So is it better to create all these functions in a external js file or no create a controller like validation_controller.js and use there?


I recommend you get as far as you can without writing a single bit of JavaScript first - see HTML form validation Client-side form validation - Learn web development | MDN

Note: This is not server validation (but neither is Stimulus), but it can get pretty far.

You can validate fields being required, values based on regex, number values with min/max and all with native browser support.

Once you have done that, including have read about building an accessible form (using for on labels etc), you can see what gaps you need JavaScript for and hence Stimulus.

At that point, it is better to focus on a field at a time and making a controller that does something specific for a field.

For example

<div class="field">
  <label class="label" for="username">Username</label>
  <div class="control">
    <input class="input" data-controller="validate" data-validate-option='{"something":true}' id="username" type="text" placeholder="joe" required pattern="[a-z]+">

Here you have some controller on the input only - this way you can keep your controllers smaller instead of having some overarching controller.

In general - it is better to try to have smaller controllers where possible (as in they are focused on a smaller area of the DOM). However, if you need to validate some field against another field you may need to rethink this approach.

1 Like