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

Update the value of the following element

In the table, each row has three text fields. <tr> <td><input type="text" data-type="number" name="qty[]" /></td> <td><input type="text" data-type="number" name="ucost[]" /></td> <td><input ty ...

Exploring a section of a react-chartjs Pie chart

I'm currently exploring how to create a static Pie chart using react-chartjs-2. Wanting to make one slice stand out more than the others, I aim to have it appear larger: My focus is on accessing a specific slice in the pie chart and adjusting its out ...

Button fails to display as intended despite meeting conditions

I'm currently using a formData object with useState(). Whenever a field is updated in the form, I update formData like this: setFormData({...formData, [field.id]: field.value}) My goal is to have the button at the end of the form change once all req ...

Using JavaScript to extract variables from parsed JSON data

Could someone please help me understand how to run this code smoothly without encountering any errors? var test = 'Something'; JSON.parse('{"xxx": test}'); I am inquiring about this because I have a JSON object containing variables th ...

Setting a default action for an Ext.Ajax.request error situation

In my application, I frequently make ajax requests using the Ext.Ajax.request method. Often, I find myself skipping error handling for failed requests due to time constraints or lack of interest in implementing fancy error handling. As a result, my code us ...

Highlighting of Vue directives in HTML within WebStorm

Can the Vue attributes and directives be highlighted? Including those in quotes. ...

What is a way to execute a series of requests using rxjs similar to forkJoin and combineLatest, without needing to wait for all requests to finish before viewing the results?

Consider you have a list of web addresses: urls: string[] You create a set of requests (in this instance, utilizing Angular's HTTPClient.get which gives back an Observable) const requests = urls.map((url, index) => this.http.get<Film>(url) ...

Utilize images inputted via an HTML DOM file uploader within p5.js

I'm facing a challenge with allowing users to upload their image file through a DOM file uploader (<input type="file"></input>). Once the image is uploaded, I'm unsure of how to transfer it to JavaScript and process it using p5.js. Ho ...

Retrieving visual information from Google Street View entity

Looking for a solution to extract imagery from the Google Street View panorama within a web page? In my program, I navigate specific routes using Google Street View's javascript API controlled by an embedded Java applet on the same page. I am seeking ...

Keeping Chart.JS Up to Date: Updating Only Fresh Data

When a button is pressed on my website, a Bootstrap modal containing a Chart.JS is called. The data for this chart is loaded via an Ajax call as shown below: function loadReports(data) { $.ajax({ type: "POST", url: "Default.aspx/getRep ...

Leveraging the power of NextJS and Strapi: Efficiently fetching multiple API pages with a single getStaticPaths

Both NextJs and Strapi offer guidance on fetching data from a single collection type within Strapi. The process involves the following code snippet: const pages = await (await fetch(getStrapiURL("/pages"))).json(); const paths = pages.map((page) => { ...

Updating the state of Formik

Currently, I'm knee-deep in a React project that requires a slew of calculations. To manage my forms, I've turned to Formik, and for extra utility functions, I've enlisted the help of lodash. Here's a peek at a snippet of my code: impor ...

The function inputLocalFont.addEventListener does not exist and cannot be executed

Help needed! I created a code to add images using PHP and JS, but I'm encountering an error in my JS that says: inputLocalFont.addEventListener is not a function Here's the code snippet: <div> <img src="<?php echo $img_path.& ...

Managing input jQuery with special characters such as 'ä', 'ö', 'ü' poses a unique challenge

Hey there, I'm running into a bit of trouble with my code and I can't figure out why it's not working. Here's a brief overview: I created my own auto-suggest feature similar to jQuery UI autosuggest. Unfortunately, I'm unable t ...

The reason why React.js does not automatically bind its functions to the "this" object

I cannot understand the purpose of a function not being bound by this object. In my opinion, all functions should be bound by 'this'. So why doesn't Reactjs automatically set bind(this) by default? For instance, in the code below, if I didn& ...

What is the best way to utilize date-fns for formatting a date retrieved from an API?

After receiving data from an API in the 'yyyy-MM-dd' format, I encountered a display issue when trying to convert it to 'dd-MM-yyyy'. How can I properly adjust the date format without disrupting the table display? onMounted(async () =& ...

What are some techniques for ensuring a CSS div remains stable and intact when adjusting the browser size?

Is there a way to prevent the entire website from resizing when you minimize or maximize your browser? I want the website size to adjust in proportion to your resize without reorganizing everything. How can this be achieved while maintaining the site lengt ...

NPM - Include in package.json without installation

Can a command be executed to validate that the package is a legitimate npm package, include it as a dependency in package.json, but refrain from actually installing it? This question arises from the need to utilize a specific package globally and incorpor ...

Adjust width based on value dynamically

I currently have a div that is sized at 250px, housing 3 child divs within it. My goal is for each of these 3 divs to dynamically scale based on their respective values, eventually reaching 100% width. This is the code snippet I am working with: <di ...

Determine the type of a nested class within TypeScript

Utilizing nested classes in TypeScript is achieved through the following code snippet: class Parent { private secret = 'this is secret' static Child = class { public readSecret(parent: Parent) { return parent.secret } } } ...