Setting a validation message for a Vuejs username input while enforcing a maximum character limit

<script>
export default {
  name: "Register",
  props: {
    msg: String,
  },
};
</script>
<style scoped>
* {
  box-sizing: border-box;
}

div {
  padding: 0;
  margin: 0;
  font-family: system-ui;
}

.red {
  color: red;
}
<template>
  <div class="pop-up-mask">
    {{ msg }}
  <div class="input-wrapper"> 
          <div class="name-icon"></div>
            <input type="text" class="input-section" 
           placeholder="Enter your Name" :maxlength="max" v-model="text" />
         
        </div>
        </div>
        </template>


--------------in main.js--------------

new Vue({
 data: {
    max: 36,
    text: ''
  }
  render: h => h(App),

}).$mount('#app')
   

It is essential to keep the input text within a limit of 30 characters. If exceeded, a message saying “You can enter 30 characters only.” should be displayed. Although conditions were set in both the template and main.js file, the functionality is not working as intended.

Answer №1

Consider utilizing the watch method

For more information, refer to the official Vue.js documentation on 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>

Answer №2

Although client-side validation has its benefits, I suggest implementing server-side validation for the username instead. In this case, if the username is already taken or exceeds the character limit, the server should return a status code of 400. Your frontend can then handle this response to display an appropriate error message when a submission fails.

Answer №3

insert the following code snippet: :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 the line below to the code: 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)
            }
        }
    }

include disable: null in the data section

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

If needed, you can display 'You can enter 30 characters only' conditionally

template

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

watch this.show = true

data show: false,

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way for me to obtain a selection of 20 random items from this JSON data

When working with my JSON data using Myjson.slice(1, 20), I encountered a situation where I needed to extract only 20 items from a dataset that had a length of 2624. In the code snippet provided, I attempted to use the slice method but struggled to differe ...

Using the foreach Loop in Javascript and AngularJs

Having trouble with a foreach loop because you're not sure of the column name to access specific data? Here's a solution to display all columns along with their corresponding data: angular.forEach(data, function(value, key) { console.log( &a ...

Adjust the height of the Iframe to match the content within it

After conducting my research, I have not been able to find a solution. Although I am not an expert in jQuery, it seems that the code is not functioning properly. Within the iframe are links that expand when clicked to display content. However, the height o ...

What is the best way to concatenate a data object?

This task should be quite straightforward. Using Vanilla JS, I am trying to update the content of a span element with the session ID obtained from a function call. Here's an example: sessionId = 0_77b1f7b5-b6c8-49a0-adbc-7883d662ebba document.getEle ...

Chrome experiences a hidden stalling issue due to a large WebGL texture

While working with WebGL on Windows 10 using Three.js, I noticed that initializing a large (4096 x 4096) texture causes the main thread of Chrome to stall for a significant amount of time. Surprisingly, the profiler doesn't show any activity during th ...

React-redux: Data of the user is not being stored in redux post-login

Hello everyone, I am fairly new to using react-redux and I'm currently facing an issue with storing user information in the redux store after a user logs in. I am utilizing a django backend for this purpose. When I console out the user in app.js, it ...

The use of 'v-on' directives mandates a value or a verb modifier (such as 'stop' or 'prevent')

I made two files, naming them Tasks.vue and Task.vue. From Task.vue, I initiated an action called 'delete-task'. Now, I aim to trigger the same action in Tasks.vue using @delete-task eslint-plugin-vue throws the following error: 'v-on&apo ...

Blackberry Browser's Window.Opener Feature

Does anyone else experience issues with the blackberry browser(5.0) and the javascript window.opener function? I couldn't find much help on Google regarding this problem. We have a pre-existing website that successfully populates parent window form f ...

Live alerts on the AWS platform (serverless)

Currently, I am working on implementing real-time notifications for my web application in AWS using TypeScript and Vue. The setup involves an RDS instance (mysql), Node.js Lambda functions for the backend, and S3 for the application storage. I am wonderin ...

When the down key is pressed in a textarea, choose the list item

I have HTML similar to the following <div class="row"> <textarea id="txtArea" ng-model="input" ng-change="handleOnChange(input);getSearchField(input);" ng-click="search(input)" ng-focus="search(input);" ...

Looking for assistance with deleting a child element in an XML file using PHP

I need help figuring out how to delete a child from my jobs.xml file with a PHP script. My jobs.xml file looks like this: <jobs> <event jobid="1"> <title>jobtitle</title> <desc>description</desc> &l ...

Using AngularJS to load a custom JavaScript file within an ng-view

In my sample project, I have utilized Angular Js for the front-end. I have developed a template and implemented dynamic loading of views based on requirements. For this application, I am utilizing angular, jquery, and cusotm js. The structure of my templat ...

The ActivatedRoute.routeConfig object appears to be empty in an Angular 2 project built with Angular-cli

Two projects I've created using angular-cli are working perfectly fine. However, in one of them, the routeConfig is showing as null and I can't figure out what's causing this issue. Both projects have identical package.json files, so there ...

I have a few inquiries about my nodejs studies. Can you assist me, please?

As I delve into my studies of nodejs, some burning questions have arisen. Is it true that nodejs supports all JavaScript? In the official documentation, it mentions using the latest v8 engine. However, I have reservations about whether all JavaScript ...

The Google Maps JavaScript API is displaying a map of China instead of the intended location

After multiple attempts, I am still facing an issue with setting up the Google Map on my website. Despite inputting different coordinates, it consistently shows a location in China instead of the intended one. Here is the code snippet that I have been usin ...

What is the best way to incorporate plugins designed for various jQuery versions onto a single webpage?

I have integrated three jQuery scripts into an HTML page, including a Colorbox plugin for the gallery, a popup plugin for a reservation form, and a sliding jQuery script for the footer. However, I am facing issues where either the close button on the pop ...

Utilizing HTML5 for page-relative translation

Is there a way to apply a translate to an element so it moves to a specific point on the page instead of relative to its starting position? For instance, in the code snippet below, the "card" elements will move 50, 100 relative to their initial position. ...

The application ceases to function properly following the update of npm and node on MacOS

I made a huge mistake by updating npm and node versions from 3.10.10 and 6.10.2 to 5.6.0 and 9.3.0, respectively. Now my app is not functioning properly and I am feeling quite desperate. Every time I try to run it, I encounter the following error: /Users ...

Mouseover function ceases to function once an element is dropped

After referencing this discussion, I successfully managed to drag items from one scroll overflow to another. However, the issue arises when these items (or their clones) are in the other scroll overflow as they do not respond to .mouseover(). The goal is ...

Deciding between Document.createElement() and Document.createTextNode() in Javascript

I'm currently exploring the distinctions between these two code snippets: // first one var h1 = document.createElement('h1'); var t = document.createTextNode('hello'); h1.appendChild(t); document.body.appendChild(h1); // second o ...