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

Discovering methods to store browser credentials securely in jQuery

I need to prevent the login button from being enabled when either the username or password fields are empty. Check out the code snippet below: $(document).ready(function(){ $('input').on('keyup blur mouseenter', function(e) { ...

The instantiation of the cloudinary module failed because of an error with the injector

I am currently developing a MEAN application based on the template provided by Linnovate. You can find the template at https://github.com/linnovate/mean My goal is to integrate a module called Cloudinary into my application. To achieve this, I followed th ...

Store the visible image location in memory to be used across various sections

I'm currently developing a website with a scrolling background image feature. However, whenever I navigate to another page on the site, the animation restarts from the beginning. Is there a way to cache the position so that the animation continues sea ...

Hero Sticky Transition with 100vhDivElement

My code is giving me some trouble. I want the div with text to stay at the bottom of the hero section with a transparent background. When that div reaches the top, it should stick with a black background. The issue is that I have set it in the javascript v ...

Tips for temporarily preventing a digest cycle when modifying a scope variable

Is there a way to edit an array of objects in AngularJS, linked to the view through ng-repeat, without updating the scope until all objects have been modified? Consider this scenario: I need to update each object in the array and only then reflect the ch ...

Should we make it a routine to include shared sass variables in each vue component for better practice?

Within my Vue application, there are numerous components that rely on shared variables like colors. I'm considering having each component import a global "variables.scss" file. Would this approach have any adverse effects? ...

There are no errors in the HTML markup, however, there is an issue where the client-side rendered virtual DOM tree does not align with the

I can't seem to figure out why I keep getting this error message: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, such as nesting block-level elements inside <p>, ...

Is it possible to determine the success or failure of an asynchronous function when the function itself already handles errors?

The architecture of my app is currently set up with functions that are scoped to specific modules, such as "Auth" for instance: async function authenticate(email) { let authenticated = false; try { if (email) { if (!validEmail(email) ...

Presentation: Troubleshooting Ineffective CSS3 Transitions

I have created a basic slideshow that can accommodate multiple images. Clicking on an image should move to the next slide, and once the last image is clicked, it should loop back to the first slide. The functionality of transitioning between slides seems ...

Why is it that a click event outside of an HTML element cannot be detected in this Vue 3 application?

I've been diving into building a Single Page Application using Vue 3, TypeScript, and The Movie Database (TMDB). Currently, I'm focused on developing a search form within my project. Within the file src\components\TopBar.vue, here&apo ...

Here is a method to transform the JSON object into a string as demonstrated below:

Presented below is a JSON object: { "category": "music", "location": { "city": "Braga" }, "date": { "start": { "$gte": "2017-05-01T18:30:00.000Z" }, "end": { "$lt": "2017-05-12T18:30:00.000Z" } } } I am looking t ...

Ajax requests are returning successful responses for GET and POST methods, however, no response is being received for

When I make a POST request within the same domain ( -> ), the responseXML contains the expected data. However, when I make the same request as a PUT, the responseXML is null for a successful request. I have tried using jQuery.ajax and even implemented it m ...

Sending information to a jQuery UI Dialog

I'm currently working on an ASP.Net MVC website where I display booking information from a database query in a table. Each row includes an ActionLink to cancel the booking based on its unique BookingId. Here's an example of how it looks: My book ...

Modify the ColVis Appearance in Datatable Using JavaScript

Where can I modify the background color for the 'Hide/Show columns' label in the ColVis.js file? ...

Improving Performance of a Large Unordered List using JavaScript

My website currently features a search box that retrieves images and displays them in a list format. Each image has an associated click event that triggers an overlay on the parent li element when clicked. However, with search results exceeding 300 images ...

What is the best way to insert an object at a particular position within an array containing numerous nested objects?

This is the given Object: [ { "id": "1709408412689", "name": "WB1", "children": [ { "id": "1709408412690", "n ...

How can we efficiently generate ReactJS Router for Links and seamlessly display a unique page for each Link?

Currently, I have an array of objects named titleUrl, which contains titles and URLs retrieved from an API. To display these as links on the sidebar, I am utilizing a custom component called MenuLink. The links are generated by iterating over the keys in t ...

Why isn't the nested intricate directive being executed?

After watching a tutorial on YouTube by John Lindquist from egghead.io, where he discussed directives as components and containers, I decided to implement a similar structure but with a more dynamic approach. In his example, it looked something like this ...

Store the text area content as a JSON object

What is the best way to store the content of a textarea in JSON format? I am currently working on a project where I have a textarea element and I need to save its value into a JavaScript object. Everything is functioning correctly except when 'enter ...

The access to the HTTP response object is not possible: the property is not found on the Object type

I recently created a response object and assigned it to the "this" object. However, when I try to access the datacentersinfo property, I encounter an error stating that the property does not exist on type Object. Due to this issue, I am unable to generat ...