/ Gists / Input validation composable
On gists

Input validation composable

Vue.js

validation.js Raw #

/*
vylepseny priklad o nazev pro v-model 
*/


import { ref, watch } from 'vue'

export function useFormValidation(initialValue, propName = 'value') {
  const value = ref(initialValue)
  const error = ref('')

  watch(value, (newValue) => {
    if (newValue.length < 3) {
      error.value = 'Value must be at least 3 characters'
    } else {
      error.value = ''
    }
  })

  function validate() {
    if (value.value.length < 3) {
      error.value = 'Value must be at least 3 characters'
    } else {
      error.value = ''
    }
  }

  return { [propName]: value, error, validate }
}

component.vue Raw #

<template>
  <div>
    <input v-model="value" @input="validate" />
    <p>{{ error }}</p>
  </div>
</template>
<script>
import { defineComponent } from 'vue'
import { useFormValidation } from './formValidation'

export default defineComponent({
  setup() {

  const { inputValue, error, validate } = useFormValidation('', 'inputValue')
  return {
    inputValue,
    error,
    validate
  }
    
  }
})
</script>