<q-input
v-model="userForm.mobile"
type="text"
label="Mobile"
counter
maxlength="10"
color="info"
lazy-rules
:rules="[
(val) => (val && val.length > 0) || 'Mobile number is required',
(val) =>
(typeof val !== number) ||
'Mobile number should be valid',
]"
/>
I'm trying to do 2 validations, but this is not working, Trying to return an error if is it empty or not a number Really appreciate it if somebody could help thanks.
CodePudding user response:
It seems your validation flow is fair, but you misspelt the Number
keyword. It's highly recommended to define your validation methods in the methods section.
I wrote you a simple sample:
<template>
<q-form @submit="submit">
<q-input
counter
lazy-rules
type="text"
label="Mobile"
maxlength="10"
color="info"
mask="##########"
:rules="[requiredRule, mobileRule]"
v-model="userForm.mobile"
/>
<q-btn
type="submit"
label="Submit"
/>
</q-form>
</template>
<script>
export default {
name: 'BaseInputValidation',
data() {
return {
userForm: {
mobile: null,
},
};
},
methods: {
requiredRule(val) {
if (!val) {
return 'Mobile number is required';
}
return true;
},
mobileRule(val) {
if (!/^\d{10}$/.test(val)) {
return 'Mobile number should be valid';
}
return true;
},
submit() {
// Do submit
},
},
};
</script>
I separate rules into methods to boost the render speed. You can also merge rule functions or define them in a global file to reuse elsewhere.
I filled the mask prop to limit the input value to a-ten-number-only input.
I used a plain regex to check numbers, it's better to be replaced with a better one :-)