q-input has value then only Rules will apply
Asked Answered
I

2

7

If q-input has value != '' then only i want to apply the Rules like required 8 number maximum. In the below code it gives me the required input error even it's null.

<q-input
    filled
    name="landline"
    label="Landline Phone Number"
    v-model="user.landline"
    placeholder="Landline Phone Number"
    ref="landlinePhoneNumber"
    type="number"
    :maxlength="8"
    :rules="[val => val!='' && val.length > 7 || 'Landline Required 8 digit']"
/> 
Ingrained answered 4/2, 2021 at 5:51 Comment(2)
try lazy-rules="ondemand" quasar.dev/vue-components/inputSaeger
np:) I've added the answerSaeger
S
8

Try to add prop lazy-rules. By default, it's set to 'ondemand', which means that validation will be triggered only when the component’s validate() method is manually called or when the wrapper QForm submits itself. More info

Saeger answered 10/2, 2021 at 13:37 Comment(2)
then you can accept the answer and upvote it ;)Saeger
Not capable of a vote now. Don't worry once I reach up to level I will upvote it.Ingrained
K
3

You have to return true when the field is null first, then validate only if it's not null. Also, add the prop lazy-rules so that it only validates when the form field loses focus.

Here is how I did it in Vue 3, using composable and TypeScript. The form field component:

<q-input
        class="q-mt-md"
        filled
        v-model="id_number"
        label="ID Number "
        type="text"
        hint="Optional/Leave blank if not available"
        lazy-rules
        :rules="[(val) => isNumberBlankOrValid(val) || 'Invalid ID Number']"
      />

The method isNumberBlankOrValid called from the field above:

    const isNumberBlankOrValid = (val: string) => {
    if (val.length === 0) {
      return true
    }
    return isValidNumber(val)
  }

The isValidNumber for other fields that must be filled:

const isValidNumber = (val: string) => val && isNumeric(val)

The isNumeric method is a simple regex for validating numbers:

const isNumeric =  (value: string) => {
  return /^\d+$/.test(value)
}
Kaciekacy answered 29/8, 2022 at 12:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.