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']"
/> 
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Shubham Sankpal
  • 133
  • 2
  • 10

2 Answers2

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

Dvdgld
  • 1,984
  • 2
  • 15
  • 41
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)
}
James Shisiah
  • 353
  • 4
  • 14