Almost EVERYONE who tried headless systems said they saw benefits. Download the state of CMS now!

Storyblok now on AWS Marketplace: Read more

O’Reilly Report: Decoupled Applications and Composable Web Architectures - Download Now

Empower your teams & get a 582% ROI: See Storyblok's CMS in action

Skip to main content

How to do validations in fieldtypes

  • FAQ
  • How to do validations in fieldtypes

Following an example of how you could do input validation in plugins. Instead of using v-model on your inputs you need to listen on the input event and pass your data only to the model if it is valid.

const Fieldtype = {
  mixins: [window.Storyblok.plugin],
  template: `
    <div>
      <input
        class="uk-width-1-1"
        type="number"
        @input="validate"
        :step="1"
        ref="input"
      />
      <div v-if="invalid">
        The number must be higher than 1 and lower than 5
      </div>
    </div>
  `,
  data() {
    return {
      invalid: false
    }
  },
  methods: {
    initWith() {
      return {
        plugin: 'number-restricted',
        value: null
      }
    },
    validate(e) {
      let val = parseInt(e.target.value)
      let max = 5
      let min = 1
      if (val > max || val < min) {
        this.invalid = true
      } else {
        this.invalid = false
        this.$refs.input.value = val
        this.model.value = val
      }
    },
    pluginCreated() {
      this.$nextTick(() => {
        if (this.model.value === null) {
          this.model.value = this.options.default || '4'
          this.$refs.input.value = this.model.value
        }
      })
    }
  },
  watch: {
    model: {
      handler (model) {
        this.$emit('changed-model', model)
      },
      deep: true
    }
  }
}