Implementing validation and displaying fields with v-model in vue.js

Looking at this code snippet:

<button type="button @click="editing=true">Edit</button>
<form v-show="editing" @submit="onSubmit">
   <textarea v-model="text"></textarea>
</form>
<div> Current value: {{text}} </div>

new Vue({ //...
   data: {
     editing: false,
     text: 'initial value..'
   }
   methods: {
     onSubmit: function() { if (this.value.length < 5) alert("error") }
   }
}

Is there a way to ensure that the {{text}} only displays a validated value without creating two separate data members for form input and display? Managing multiple data members can lead to complexity, especially with large forms.
Perhaps there is a v-model update hook that can handle validation?
The main question here is if it's feasible to avoid the need for dual data members.

Answer №1

v-model applied to a

<textarea></textarea>
can be interpreted as:

<textarea
    v-bind:value="text"
    v-on:input="text = $event.target.value">

To address your previous inquiry, it seems there are no hooks available. You have the option to either avoid using v-model by utilizing the approach mentioned above or employ a separate variable to store the most recent valid string, as you had considered. The latter could be implemented like this:

const app = new Vue({
  el: "#app",
  data: {
    editing: false,
    text: 'Initial value..',
    lastValid: 'Initial value..',
  },
  watch: {
    text(value) {
      if (value.length > 4) {
        this.lastValid = value;
      }
    },
  },
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div>
    <form>
      <textarea v-model="text "></textarea>
    </form>
    <div> Current value (length > 4): {{lastValid}} </div>
  </div>
</div>

Answer №2

To ensure the validity of input (e.g., length must be >= 5), you can save the last valid input and update it with every keydown event. Then, during submission, send the last valid value that was stored.

new Vue({
 el: '#app',
 data() {
  return {
   text: 'initial value..',
   lastValid: 'initial value..'
  }
 },
 methods: {
  submit() {
    alert(this.lastValid)
  },
  textChange($event) {
    let newText = $event.target.value
    this.lastValid = newText.length < 5 ? this.lastValid : newText
  }
 }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>

<div id="app">
  <form>
    <textarea v-model="text" @keydown="textChange"></textarea>
    <input type="submit" value="Send" @click="submit" />
  </form>
  {{ lastValid }}
</div>

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

Can the caller function's arguments be altered using Function.prototype.apply()?

function modifyValues(a,b){ console.log(arguments); //["oldValue","oldValue"] var newArguments = updateValues.apply(this,arguments); for (var i=0;i<arguments.length;i++){ arguments[i] = newArguments[i]; } console.log(arguments); // ...

Providing a user with a special discount tailored to their email address?

<script type="text/javascript"> function updatePrice() { var price = document.getElementById("product").value; var size_price = document.getElementById("size").value; var a=parseInt(price);//parsed type price var b=parseInt(size_price);//pa ...

Unexpected JSON token error occurs in jQuery when valid input is provided

I encountered an error that I'm struggling to pinpoint. The issue seems to be related to the presence of the ' symbol in the JSON data. After thoroughly checking, I am positive that the PHP function json_encode is not responsible for adding this ...

What steps can I take to ensure that the content remains intact even after the page is

Hey there, I hope you're having a great start to the New Year! Recently, I've been working on creating a calculator using HTML, CSS, and JavaScript. One thing that's been puzzling me is how to make sure that the content in the input field do ...

JavaScript issue causing input fields to malfunction and clear text boxes

I apologize for the simplicity of this question, but I am struggling with an issue and seeking help. Here's the problem: my calculate() method is not clearing text input as expected when testing my page. Below is the HTML markup and script: <!DOC ...

Leveraging Node.js to fetch data from a third-party website API using JSON

This particular code is currently not functioning properly as it is unable to retrieve an address from an external website We need the "result" value that is present in that json file. Is there a straightforward solution for this issue, such as enabling ...

Implementing scroll-based animations in VUE.JS with a similar effect to wow.js

Is there a way to incorporate animation into certain blocks while scrolling on my Vuejs website similar to wow.js? If you have any suggestions, I would greatly appreciate it. Thank you! ...

Difficulty encountered when utilizing an if statement within a function

I have encountered a simple issue while using an if statement within a function. The following code is working as intended: <!DOCTYPE html> <html> <body> <h1>Typewriter</h1> <button onclick="typeWriter()">Click me& ...

Getting Permission in the latest Facebook JavaScript SDK: A Step-by-Step Guide

I've been working on transitioning to the new Facebook JavaScript SDK from the old JavaScript library (where I was using Connect) and unfortunately, I'm facing issues with getting the permission dialog to pop up. My goal is to display the permiss ...

Explore vue3 components using vue-test-library and universal components

I started creating unit tests for a production app using jest, @testing-library/vue, and supporting libraries. The first test I created is as follows: import vue from "vue"; import { render } from "@testing-library/vue"; import LibBtn f ...

Tips for categorizing items retrieved from .getJSON based on their category property

Looking to display a menu of coffee items with their respective parent categories on the page? Here's how you can start: Category Title Item Item Item Item Category Title Item Item This is what my data model looks like: { "menuItems": [ ...

Using dynamic variables in the $.getJSON function

This specific inquiry represents my current goal, with an added layer of complexity. My aim is to streamline the process by creating a single 'fetchData' function in my VueJS project that can retrieve multiple JSON files without duplicating code ...

Looking for assistance grasping the concept of using a for loop in MongoDB's aggregate method

This code snippet is designed to maintain the order of an array (var list) when utilizing mongoDb's $in clause effectively. Although, I must admit that the logic behind it is not entirely clear to me. I can see that it's iterating in reverse to ...

Error: Certain Prisma model mappings are not being generated

In my schema.prisma file, I have noticed that some models are not generating their @@map for use in the client. model ContentFilter { id Int @id @default(autoincrement()) blurriness Float? @default(0.3) adult ...

Transferring the values of JavaScript objects to HTML as strings

My goal is to generate HTML elements based on the values of specific JavaScript objects that are not global variables. However, when attempting to execute the code below, I encounter an error stating "params is not defined." What I actually aim to achieve ...

"Troubleshooting: Issue with AngularJS ng-click Functionality Not Working on Re

Having trouble with the ng-click function in AngularJS when using the following HTML code: <tr ng-repeat="ai in alert_instances" ng-click="go('/alert_instance/{{ai.alert_instancne_id}}')"> <td>{{ai.name}}</td> <td>{{a ...

What is preventing window.scrollTo() from being executed?

I have implemented Bootstrap's Buttons plugin to toggle the state of a custom checkbox. When the button is toggled on, a hidden element should appear at the top of the page and then the page should scroll to the top. Similarly, when the button is togg ...

Only certain fields are returned by JQuery's form serialize() method

Encountering an issue with the serialize() function in jQuery when attempting to submit a serialized form via AJAX. Some of the field values are not being retained. Suspecting a problem with either my HTML structure or jQuery code: <div id="register" ...

Looking to conceal the edges of a ThreeJS box primitive

I'm trying to figure out how to hide the edges displayed in a box primitive using ThreeJS. The edges only appear when I apply a texture to the faces. I've attempted various options such as setting wireframe=false, but the edges persist. Here&ap ...

Using Vue router to bind a class to links and highlight the active class

I am currently working on a project where I need to render a sidebar with links to different pages. The challenge I'm facing is that these sidebar items should have different styles when they are active. Unfortunately, I am unsure of how to create a b ...