vuejs - Combining multiple criteria to enable form submission

Is there a simple way to validate my input?

I want to ensure that the input is not empty and a checkbox must be checked before enabling the submit button.

Currently, I have successfully bound the condition for the checkbox, but I'm unsure how to also bind the input.length != 0 condition.

Here's the current code:

<template>
<b-field grouped>
 <b-input
  placeholder="E-Mailadresse"
  type="email"
  icon-pack="far"
  icon="envelope"
  expanded
  v-model="input"
  >

 </b-input>
 <button class="button" @click="isActive = !isActive" :class="[checked ? 'is-success' : 'is-white is-outlined']" :disabled="!checked">Subscribe</button>

</b-field>
<div class="field">
 <b-checkbox v-model="checked">
 <p>We use the services of <a href="link to newsletter company">Newsletter</a> to send our newsletters. We need your email address to send you these newsletters. Please confirm that we are allowed to collect your data. For more information, refer to our <a href="link to privacy">Privacy Policy</a>.</p>
 </b-checkbox>
</div>
<b-message title="Thank you!" type="is-success" has-icon :active.sync="isActive">
 Your newsletter subscription has been successful. Please confirm the Double-Opt-In link in the confirmation email.
</b-message>
</template>
<script>
export default {
  data () {
    return {
      checked: false,
      isActive: false
    }
  }
}
</script>

I've heard that computed properties might help with this issue, but I haven't been able to make it work yet.

Any advice would be greatly appreciated!

Answer №1

If you wish to hide or disable a button when there is no input or checkbox is unchecked, using a computed property is the recommended approach. It seems you have included v-model="input" without defining a corresponding data property.

Below is an example of how this can be achieved:

Vue.use(Buefy.default)
var App = new Vue({
    el: '#app',
    data:function(){
    return {
        checked: false,
        isActive: false,
        email: null
      }
    },
    methods:{
    log(){
      console.log(arguments)
      }
    },
    computed: {
    validDataAdded: function(){
       return this.checked && this.email && this.email.length > 0;
      }
    }
})
#app {
  margin: 2em;
}
.v-cloak{
  display: none;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Buefy</title>
<link rel="stylesheet" href="https://unpkg.com/buefy/lib/buefy.css">
</head>
<body>
<div id="app" v-cloak>
<b-field grouped>
 <b-input
  placeholder="E-Mailadresse"
  type="email"
  icon-pack="far"
  icon="envelope"
  expanded
  v-model="email"
  >

 </b-input>
 <button class="button" @click="isActive = !isActive" :class="[validDataAdded ? 'is-success' : 'is-white is-outlined']" :disabled="!validDataAdded">Subscribe</button>

</b-field>
<div class="field">
 <b-checkbox v-model="checked">
 <p>Wir nutzen für den Versand unserer Newsletter den Dienst <a href="link to newsletter company">Newsletter</a>. Wir benötigen deine E-Mailadresse, um dir Newsletter schicken zu können. Bitte bestätige das wir deine Daten erfassen dürfen. Weitere Informationen findest du in unserem <a href="link to privacy">Datenschutzhinweis</a>.</p>
 </b-checkbox>
</div>
<b-message title="Danke!" type="is-success" has-icon :active.sync="isActive">
 Deine Newsletteranmeldung ist erfolgt, bitte bestätige nun den Double-Opt-In-Link in der Besätigungsemail.
</b-message>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/buefy"></script>
</body>
</html>

It's important to note that this validation will not enforce a specific input type for email, but rather check if any information is entered in the email field.

Answer №2

If you want to enhance your button functionality and customize its appearance, you can create a method block with a specific function for this purpose:

<template>
  <b-input
    placeholder="E-Mailadresse"
    type="email"
    v-model="mail"
    v-bind:class="classMail"                 
   @change="checkMail()"
  >
  </b-input>
  <button class="button" :class="classSubmitMail"
        @click="isActive = !isActive"    
        :disabled="mailOk">
    Subscribe
  </button>
...
</template>
<script>
export default {
  data () {
    return {
      email: '',
      checked: false,
      isActive: false,
      mailOk: false,
      classMail: 'is-what-you-nead'
      classSubmitMail: 'is-gray'
    }
  },
  methods: {
     checkMail: function () {
       this.mailOk = false
       // perform regex checks on mail .. .
       // this.mailOk = ... 
       //this.classMail = 'is-...'
       if (mailOk && this.checked) {
         this.classSubmit = 'is-success'
         this.classMail = 'is-success'
       } else {
         this.classSubmit = 'is-warning'
       }
    }
  }
}

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

What are the benefits of opting for <router-link> compared to using <a href="">?

When utilizing vue-router, the component known as <router-link> is available for linking to various routes. For instance: <router-link to="/foo">Link</router-link> Nevertheless, it appears that the subsequent code accomplishes a similar ...

How to include an href in a button using Pug without disrupting a form

Is there a way to create a button that redirects to my /leaderboard page once my quiz app submits? h1 Play Time 4 Trivia! button Go form(method='POST') ul each val in questions li ...

The JQUERY Click event fails to trigger only on the initial click

While attempting to display the name stored as a data value for each button in the code, I encountered an issue where it wouldn't work on the first click event call. However, after the initial click, it operated normally. It is important to note that ...

Converting constants into JavaScript code

I've been diving into typescript recently and came across a simple code snippet that defines a constant variable and logs it to the console. const versionNuber : number = 1.3; console.log(versionNuber); Upon running the tsc command on the file, I no ...

Declaring a function within a conditional statement

I recently came across a code sample in the book You Don't Know JS: Scope & Closures that is puzzling to me. "Function declarations that appear inside of normal blocks typically hoist to the enclosing scope, rather than being conditional as this ...

Creating JavaScript objects through function calls

let getBoxWidth = function() { this.width=2; }; alert(getBoxWidth.width); Hello there! Can you explain why the output is undefined in this scenario? ...

No response data being displayed after Angular post request

After sending a POST request via Postman, I received the expected response with a status of 400. However, when I tried sending the same request using Angular's http.post in the browser, I only received a 400 error without any response data. https://i ...

Tips on executing a $.get request while submitting a form?

Instead of using AJAX to submit my form, I am trying to implement a progress bar by making GET requests to the server while the form is submitting. This is particularly important when dealing with multiple file uploads that may cause the submission to take ...

Guide on transforming the best.pt model of YOLOv8s into JavaScript

After successfully training a custom dataset on YOLOv8s model using Google Colab, I now have the best.pt file that I want to integrate into a web app via JavaScript. I've come across mentions of TensorFlow.js as a potential solution, but I'm stil ...

The Model.findById() function is producing an undefined result

I am currently working on implementing a favorite toggle feature that saves favorites in an array. I have created a Schema and a router for this functionality. However, when I attempt to test it on insomnia, I am receiving 'undefined' in my conso ...

Auto-fit HTML Webpage Resizer Simplified

Just finished my very first jQuery project, a simple full-width slider. I've been focusing on HTML & CSS and currently working with C#. The problem is that I don't want the page to be scrollable; I want it to autofit to the webpage. Imagine ope ...

I have encountered a node.js error related to the 'Require Stack'

Encountering an error in my node.js application when trying to open a .js file { code: 'MODULE_NOT_FOUND', requireStack: } Unable to determine the root cause of this issue I have tried re-installing Node.js and its packages, removed and added b ...

Translate data from two "contact form 7" date fields into JavaScript/jQuery to display the date range between them

NEW UPDATE: I was able to get it working, but the code is a bit messy. If anyone can help me clean it up, I would greatly appreciate it. <div class="column one-fourth" id="date-start">[date* date-start date-format:dd/mm/yy min:today+1days placeholde ...

What is the best way to insert text into a span element within a for loop using JavaScript?

I am currently working on form validation using an array and a loop. In each required field, I have created empty span elements. Here is the JavaScript code that I have set up: var name = document.querySelector('#Name').value, firstLastName = ...

Issue with Flex property not being supported in Safari browser

.rq-search-container { position: relative; width: 100%; background: white; display: flex; flex-direction: row; align-items: flex-start; border-radius: 2px; z-index: 30; -webkit-flex: 1 0 15em; } While this code functi ...

Using React JS to extract query string values

My current URL contains the following: http://example.com/callback?code=abcd I am trying to extract the value of "code." Here is the React code I have written: import React from 'react'; import { useEffect } from 'react'; const Callba ...

Convert XML data into a structured table format

We have an XML file named "servers.xml" that needs to be parsed. This file is located on the same server where we want it to be parsed, in the same folder. <root> <list> <server> <server name="28 Disconnects La ...

Ways to execute a script from termly on NextJS using JSX

I've been utilizing termly to assist in creating legal terms for a website I'm developing. They provided me with some HTML containing a script, but I am struggling to get it to execute on a page in JSX. I attempted to use both Script and dangerou ...

Adjust the color of the Icon within the tab in Material-UI

I'm attempting to change the color of the tab icon that is highlighted while keeping the others unchanged, but I am struggling to find a solution. I am using a MUI component inside the icon button. <Tab icon={ ...

Encountering a TypeError with Arg 1 while trying to execute the save method in jsPDF

I am currently working on a react project with a simple implementation of jsPDF. I am trying to execute the sample 'hello world' code but encountering an error when using the save method: https://i.stack.imgur.com/o4FWh.png My code is straightf ...