Customized length limits in Vue components

In the form, there is a field for the phone prefix and another one for the actual phone number. The validation needs to be dynamic, with the minimum length calculated using the formula 7 - phoneprefix.length and the maximum length as 15 - phoneprefix.length. I am struggling to implement this dynamically, even after trying various methods and approaches. Any help would be greatly appreciated. Here is my code:

    <template v-if="currentStep === 'phone'">
        <div class="q8-form-row-text">
            <span class="second" v-t="{path:'requirement_phone'}"></span>
        </div>
        <div class="q8-form-row q8-form-row_phone-group">

            <CustomSelectComponent
                    v-if="country"
                    @country="onPhonePrefixChange"
                    :options="countries"

                    v-model="country"
                    class="phonePrefix"
            ></CustomSelectComponent>

            <input v-model="phone" class="q8-form__input q8-form__input-phone" :placeholder="$t('phone')"
                   name="phone" required="required" pattern="[0-9٠-٩]+" :minlength="getPhoneLengthValidation('min')" type="tel"
                   :maxlength="getPhoneLengthValidation('max')" ref="phone"  @blur="$v.phone.$touch()"/>
            <span v-if="$v.phone.$error" class="q8-form__input-error" v-t="{path: 'error.phoneNumberError'}"/>

        </div>
        <div class="q8-form-row">
            <button type="submit" value="submit" class="q8-form__submit q8-form__submit__yellow q8-form__submit__yellow-gradient"
                    :class="{
                    'q8-form__submit_next': submitButtonType === 'next'
                }"
                    v-t="{path: submitButtonType}" @click="handleSubmitButtonClick()" :disabled="isSubmitButtonDisabled()"></button>
        </div>

    </template>

Description of Logic:

  public getPhoneLengthValidation(validationOption: 'min' | 'max'): number {
        const size = validationOption === 'max' ? 15 : 7;

        return size - this.phonePrefix.length;
    }

Validations in Vue Template:

validations: {

    fullName: {
        required,
        minLength: minLength(2),
    },
    email: {
        required,
        email,
        minLength: minLength(this.minValue),
    },
    phone: {
        required,
        numeric,
    },
    PrivacyPolicy: {
        checked: ( (value) => value === true),
    },
},

Answer №1

Kindly review the implementation example below for troubleshooting. The main issue has been identified in the custom decorator utilized:

<template>
    <div>
        <div class="form-group" :class="{ 'form-group--error': $v.fullName.$error }">
            <label class="form__label">Name</label>
            <input class="form__input" v-model="fullName" @input="$v.fullName.$touch()" />
        </div>
        <span v-if="$v.fullName.nameValidator">
            {{$v.fullName | json}}}
        </span>

        <button @click="setMinLength()" >go</button>

        <span >
            {{$v | json}}}
        </span>
    </div>
</template>


<script lang="ts">
    import {Component, Prop, Vue, Watch} from 'vue-property-decorator';
import { required, email, numeric, minLength, maxLength} from 'vuelidate/lib/validators';

Component.registerHooks(['validations']);
@Component()
export default class RegistrationFormComponent extends Vue {  

    validations() {
        return {
            fullName: {
                required,
                nameValidator: this.nameValidator
            }
        }
    }



    public fullName= '';
    public minLength:number= 3;

    nameValidator(value:string){
        return   this.minLength > value.length
    }


    setMinLength(){
        this.minLength = 5;
    }

    public created() {
    }


}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
    @import '../../assets/styles/styles.scss';
</style>

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

The SignalR client is able to receive calls from the dashboard client, however, it does not receive

I have set up two Vue.js clients that are connected to a common backend server built with ASP.NET Core. One client serves as an e-commerce platform while the other client is responsible for managing orders through an admin dashboard. Using SignalR, I succ ...

tips on displaying textbox content on a php webpage

I have a piece of code where, when text is entered into a textbox and the add attribute button is clicked, the entered value is displayed on the page twice. One appears in the first row of a table, and the other appears in the first row of a second table. ...

Get a Blob as a PNG File

Hope you had a wonderful Christmas holiday! Just to clarify, I am new to JS and may make some unconventional attempts in trying to download my Blob in PNG format. I am facing an issue with exporting all the visual content of a DIV in either PDF or image ...

Tips for maintaining the integrity of blank space within a text node?

When intercepting a paste event and cleaning HTML off of the content using textNodes, I am faced with an issue where all white space is reduced to a single space and new lines are disregarded. For example, pasting: "hello world !" ends up being "h ...

Error: Angular is encountering an issue with accessing the property 'push' as it is currently undefined

I have successfully created a news ticker that works well in my codepen example. However, I am encountering an issue with integrating it into my code structure. The error message I am currently receiving is: Cannot read property 'push' of undefi ...

A guide on attaching files to CouchDB using the Couchdb4j library

I'm facing a challenge with using a Java application to attach system files to a Couchdb database using the Couchdb4J library. Despite trying to modify the code provided, I keep encountering an unresolved error. Can anyone point out where I went wrong ...

Tips for executing a function on a specific class selector using the document.getElementsByClassName method

When I click on a specific class, I want to implement a fade-out function in JavaScript. However, I am struggling to make a particular class fade out successfully. I attempted to use the this keyword, but it seems like I might be using it incorrectly bec ...

Tips for transferring information from the Data function to AsyncData in Nuxt

Looking for a way to transfer data from the Data function to asyncData in Nuxt. I've attempted the following: data () { return { prevpage: null, nextpage: null, currentPage: 2, pageNumbers: [], pageNumberCount: 0 ...

When executing a function, the previous React state continues to linger

Why is the updateUser() function only updating the last user instead of all users despite using useCallback and including users as a dependency? The expected output after clicking the update button should be: {"id":1,"name":"John& ...

How to download a file using AJAX in Laravel?

Is there a way to download a CSV file within an ajax call? I have an ajax request in my Laravel controller that successfully retrieves the file contents in the response. However, I am facing issues with actually downloading the file. Laravel controller c ...

When making an Axios API request in Next.js, an error is encountered stating that the property 'map' cannot be read as it is undefined

Hey there! I've been trying to fetch data from the API endpoint in my NextJs application using axios. However, whenever I try to map over the retrieved data, NextJs keeps throwing the error message "TypeError: Cannot read property 'map' of ...

The exported NextJS URL isn't functioning properly

Recently, I delved into the world of Next JS by following a tutorial on YouTube by Brad Traversy. In his guidance, I used next export to export the program and ran it using serve -s out -p 8000. While the page loads perfectly on localhost:8000, the issue a ...

JQuery: Issue with closing modal on certain popups

I have configured a popup that is associated with 6 different products. While it functions correctly for the first product, it does not seem to work properly for the rest. <script> //var modal = document.getElementById("m ...

What is the reason behind bower installing packages twice?

Whenever I use Yeoman to install packages, which is powered by Bower in the background, I notice that each package gets duplicated... The first copy is placed in the project root under the components folder. The second copy goes inside the app/components ...

Tips on how to optimize form input mapping without losing focus on updates

I am facing an issue with a form that dynamically renders as a list of inputs. The code snippet looks like this: arrState.map((obj,index)=>{ return( <input type="text" value={obj} onChange{(e) => stateHandler(e,index)}<inpu ...

Tips for transferring an array from a form to a URL using JavaScript?

My form uses a get method, and includes a select element allowing users to choose multiple options. However, when the user submits the form, the URL does not neatly display these selections. Is there a way for me to pass the array in a more organized manne ...

The type unknown[] cannot be assigned to type React.ReactNode

import * as React from 'react'; import { List, ListItemButton, ListItemIcon, ListItemText, ListItem} from '@mui/material'; import LightbulbOutlinedIcon from '@mui/icons-material/LightbulbOutlined'; import NotificationsNoneOutl ...

Using Javascript to validate passwords and Bootstrap for design enhancements

I've been working on learning Javascript and some basic HTML using bootstrap v5 recently. One of the tasks I'm currently tackling is creating a Sign-in form and implementing validation for the required fields. While following the Bootstrap docu ...

Is there a method in bootstrap that reveals the elements with the hidden class?

Currently, I am loading data into a bootstrap table on my JSP. The table class is hidden at the moment. After successfully uploading the data into the bootstrap table, I have implemented the following code: $(function() { var table = $('#Table') ...

Sending a JavaScript click event using curl and PHP

Attempting to extract information from a website. The main page contains multiple option buttons along with an ACCEPT and RESET button. When the user selects options and clicks on the ACCEPT button, new content is displayed. I have a question regarding ma ...