[Vuejs]-How to set maximum limit for username with validation message in Vuejs?

0๐Ÿ‘

โœ…

Try to use watch

Official documentation
https://v2.vuejs.org/v2/guide/computed.html#Watchers

<div class="pop-up-mask">
        {{ msg }}
        <div class="input-wrapper">
            <input
                type="text"
                class="input-section"
                placeholder="Enter your Name"
                :maxlength="max"
                v-model="msg"
            />
        </div>
    </div>
<script>
  import LazyImageVue3 from 'lazy-image-vue3'

export default {
  name: 'App',
    data: () => ({
    max: 36,
    text: '',
    msg: '',
  }),
  components: {
    LazyImageVue3
  },
    watch: {
    msg(text) {
      console.log(text.length)
      if(text.length === 30) {
        this.msg = 'You can enter 30 characters only.'
        console.log('You can enter 30 characters only.')
        alert('You can enter 30 characters only.', text.length)
            }
        }
    }
}
</script>

0๐Ÿ‘

While client side validation is nice and all, I recommend you instead validate the username on the server-side and return a statuscode 400 if the username is taken or too long. Your frontend can then detect when the submit request fails and display an error message.

0๐Ÿ‘

add :disabled = 'disable == 1'

<div class="pop-up-mask">
        {{ msg }}
<p v-if="this.show">{{ text2 }}</p>
        <div class="input-wrapper">
            <input 
                :disabled = 'disable == 1'
                type="text"
                class="input-section"
                placeholder="Enter your Name"
                :maxlength="max"
                v-model="msg"
            />
        </div>
    </div>

add this.disable = 1
watch

watch: {
    msg(text) {
      console.log(text.length)
      if(text.length === 30) {
        this.show = true
        this.disable = 1
        this.msg = 'You can enter 30 characters only.'
        alert('You can enter 30 characters only.', text.length)
            }
        }
    }

add disable: null
data

data: () => ({
    text2: 'You can enter 30 characters only.',    
    max: 36,
    text: '',
    msg: '',
    disable: null,      
  }),

You can also add conditional display 'You can enter 30 characters only.'

template
<p v-if="this.show">{{ text2 }}</p>

watch
this.show = true

data
show: false,

Leave a comment