I am using FormKit in a Nuxt 3 + Vue 3 project. I wanted to add a validation check on an input textbox to ensure that if a user enters only numbers, then the user is informed that the input is invalid and must enter some text.
For example:
12345 --> INVALID input
Engineer 1 --> This is fine
The formkit documentation has this as an example: See, https://formkit.com/essentials/validation#number
<FormKit
type="text"
label="Age"
validation="number"
value="27365 days old"
validation-visibility="live"
/>
The above code ensures that a user must enter only numbers. How do I reverse this ensuring that the user cannot enter only numbers? I have tried the below but none seem to be working:
Option 1: !number
does not work
<FormKit
type="text"
label="Position"
validation="!number"
/>
Option 1: not:number
does not work (I know it cannot be used this way. Just tried it out)
<FormKit
type="text"
label="Position"
validation="not:number"
/>
Fenilli is correct that you'll want to register a custom rule for this type of thing if you need to use it across your project.
You can also achieve this inline using the array syntax for validation rules and a function that's in scope of your component in the event you only need it as a one-off.
<script setup>
const cannotBeOnlyNumbers = ({ value }) => {
const regex = /^(?![0-9]+$)[a-zA-Z0-9 ]{2,}$/
return regex.test(String(value))
}
</script>
<template>
<FormKit
type="text"
:validation="[['required'],[cannotBeOnlyNumbers]]"
:validation-messages="{
cannotBeOnlyNumbers: 'Value cannot be only numbers.',
}"
validation-visibility="live"
label="FormKit Input"
help="edit me to get started"
/>
</template>
Live playground example can be seen here: https://formkit.link/b146d29c77521f621fe04e2f3e976957
for documentation on adding a validation rule globally see: https://formkit.com/essentials/validation#adding-a-rule-globally