---
title: Adding File Validation to Lexxy Editor with Stimulus
author: Victor Cobos
tags: StimulusJS, Rails
published_at: '2025-09-17T11:58:00+02:00'
updated_at: '2025-09-17T15:29:29+02:00'
canonical_url: https://www.dotruby.com/articles/adding-file-validation-to-lexxy-editor-with-stimulus
---

# Adding File Validation to Lexxy Editor with Stimulus

A simple Stimulus controller to validate attachments in the Lexxy editor — restricting file types and sizes before they get uploaded.

When using [Lexxy](https://github.com/basecamp/lexxy) as a text editor, one thing I wanted was more control over which files users could attach. For example, I didn’t want people to upload huge videos or unsupported formats.

Since my Rails app already uses Stimulus, I wrote a small controller that listens to Lexxy’s `file-accept` event and blocks files that don’t meet the rules. This way, the editor stays lightweight, and validation logic remains in my own hands.

## Stimulus Controller for Lexxy Attachments

````
Here’s the controller file I’m using. It checks for file type and size, then prevents Lexxy from accepting files that don’t match the rules.

```javascript
// lexxy_controller.js
import { Controller } from '@hotwired/stimulus'

export default class extends Controller {
  static values = {
    maxBytes: { type: Number, default: 5 * 1024 * 1024 },
    types: { type: Array, default: ['image/jpeg', 'image/png', 'application/pdf'] }
  }

  connect () {
    this.attachments = this.element.getAttribute('attachments') !== 'false'
    if (this.attachments) {
      this._boundOnAttachmentsAccept = this._onAttachmentsAccept.bind(this)
      this.element.addEventListener('lexxy:file-accept', this._boundOnAttachmentsAccept)
    }
  }

  disconnect () {
    if (this.attachments && this._boundOnAttachmentsAccept) {
      this.element.removeEventListener('lexxy:file-accept', this._boundOnAttachmentsAccept)
    }
  }

  _onAttachmentsAccept(event) {
    const file = event.detail?.file
    if (!file) return

    if (!this.typesValue.includes(file.type)) {
      event.preventDefault()
      window.alert(`File type not allowed. We only accept ${this.typesValue.join(', ')}.`)
      return
    }

    if (file.size > this.maxBytesValue) {
      event.preventDefault()
      const maxMB = (this.maxBytesValue / 1048576).toFixed(1)
      window.alert(`File too large. Maximum ${maxMB} MB allowed.`)
    }
  }
}
```
````

## Conclusion

This example uses plain `alert()` calls to reject unwanted uploads, but in a production app you’ll probably want to show errors in a more user-friendly way.

Still, this controller provides a simple, Stimulus-friendly way to enforce rules on file uploads in Lexxy — keeping your editor flexible while giving you full control over what gets attached.
