0

I am using Vuetify and use its default way of adding rules to input fields.

I know there is this rule: v => !!v

This checks if the the form input isn't empty. But how can I make it in such a way that it only accepts alphabetical letters, numbers or even apply a regex to it? I can't find anything in the docs. Can someone with any experience help me out?

1 Answer 1

2

So I assume that you've probably sorted this now but for anyone finding this from google etc.

To add a new rule, you need to add it to your vue component, either through an import or just adding it straight to your data object. You name it as you would any other data property and it's an array of the tests like the v => !!v one you mentioned. You then add the OR operator followed by the text to show on a failed validation.

So to add a regex that only allows letters you would have this:

data () {
  return {
    alphaRule: [
      v => /[a-zA-Z]+$/.test(v) || 'Field must only contain letters'
    ]
  }
}

then on your form field you would have <v-text-field :rules="alphaRule"></v-text-field>

That said, I would highly recommend adding all of your rules to a Rules.js file and binding the rules globally so that you can access them anywhere, have a centralised repository for them, and it helps keeps your code DRY too.

I have just made a big ol list of rules inspired by Laravel's Validation rules and will edit my answer to include them oncce I have finished testing them.

EDIT Here are all the rules I'm currently using in production. Hopefully they'll help someone else! You'll need to import them into your component to use them, or you can globally include them through a vue mixin.

Sign up to request clarification or add additional context in comments.

1 Comment

Very interesting and complete answer. I am looking forward to see your validation rules! How do you import the rules from this file?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.