xyz
xyz

Reputation: 119

Validation between two text field, vuetify

I have two text-field in my vuetify app, I want that the value on the first text field must be less to the second text-field. The value of the second text-field must be greather then the first.

For example when user choose a less value in second text field then the first text field, will recieve a message that 'value can't be less'

Here is what I want to have:

enter image description here

My code is here:

First text-field

 <v-text-field
 v-model="first"
label="First text field"
readonly
v-bind="attrs"
:rules="validateTextField"
v-on="on"
 ></v-text-field>

Second text-field

 <v-text-field
 v-model="second"
label="Secondtext field"
readonly
v-bind="attrs"
:rules="validateTextField"
v-on="on"
 ></v-text-field>

script

validateTextField: [v=>  || 'value cannot be less'],

Upvotes: 2

Views: 2723

Answers (2)

mflorczak
mflorczak

Reputation: 363

This will not work because if you have dependable fields your application will still inform user about error because rules are not reactive. You can achieve reactivity with help of Vue. Input form has method validate() which will execute validation. So you can create watchers on dependable fields and call this method when value will changed. Here is an example.

<script>
const inputForm = ref<VForm>({});
const one = ref(0);
const two = ref(0);

const oneGreaterThanTwo = () => one.value > two.value || "One should be greater than Two"
const twoLessThanOne = () => two.value < one.value || "Two should be less than One"

watch(one, () => {
  inputForm.value.validate();
});

watch(two, () => {
  inputForm.value.validate();
});
</script>

    <template>
        <v-form ref="inputForm">
                  <v-text-field
                    v-model="one"
                    label="One"
                    :rules="[oneGreaterThanTwo]"
                    required
                  ></v-text-field>
                  <v-text-field
                    v-model="two"
                    label="Two"
                    :rules="[twoLessThanOne]"
                    required
                  ></v-text-field>
        </v-form>
    </template>

Upvotes: 5

sdonchor
sdonchor

Reputation: 102

Try to modify your script like that, separating the rules:

validateFirstTextField: v=> v<this.second|| 'Cannot be more than second',
validateSecondTextField: v=> v>this.first || 'Cannot be less than first'

Upvotes: 3

Related Questions