Search code examples
javascriptvue.jsvuelidate

How can I tell the validator of Vuelidate to accept "alphaNum" plus character dot(".")?


I have an input field, I can tell Vuelidate that it only accepts alphaNum and Required like this:

import { required, alphaNum } from "vuelidate/lib/validators";

export default {
  data() {
    return {
      myInputValue: ""
    };
  },
  validations: {
    myInputValue: {
      required,
      alphaNum
    }
  }
};

Here comes my question, how can I make myInputValue to accept an additional character dot(.)?

Which will total accept these things

  1. abcdefghijklmnopqrstuvwxyz
  2. ABCDEFGHIJKLMNOPQRSTUVWXYZ
  3. 0123456789
  4. .

How can I achieve this?


Solution

  • You can use a regular expression with a character set of alphanumeric characters plus .:

    import { required, helpers } from 'vuelidate/lib/validators';
    const alphaNumAndDotValidator = helpers.regex('alphaNumAndDot', /^[a-z\d.]*$/i);
    
    export default {
      data() {
        return {
          myInputValue: ""
        };
      },
      validations: {
        myInputValue: {
          required,
          alphaNumAndDotValidator
        }
      }
    };