Mohit Chandani
Mohit Chandani

Reputation: 101

Custom validation in vuelidate plugin

I have integrated Vuelidate plugin for my Nuxt project and I want to add a custom validation to it in which whenever the user inputs a URL then www. get replaced and then I can check that String with the regex (?:(?:[a-zA-Z0-9])(?:[-.][a-zA-Z0-9])?)+(?:\.[a-z]{2,6})+$

This is the way I am trying to achieve it

const customValidate = (value, vm) => {
  this.domainCheck = value.replaceAll('www.')
  return vm.domainCheck.match(
    /(?:(?:[a-zA-Z0-9])(?:[-.][a-zA-Z0-9])?)+(?:\.[a-z]{2,6})+$/
  )
}

data(){
 return{
  domainName: ''
  domainCheck : '' 
 }
}

validations:{
 domainName:{
   customValidate
 }
}

Is there a way to achieve this or only possible after submitting the form and there checking for the validation?

Upvotes: 1

Views: 369

Answers (1)

Mohit Chandani
Mohit Chandani

Reputation: 101

Looks like I found the solution to my problem I did it in the following way:

const customDomainCheck = (value) => {
  let domainCheck = ''
  if (value.includes('www.')) {
    domainCheck = value.replaceAll('www.')
  }
  if (domainCheck) {
    // eslint-disable-next-line prefer-regex-literals
    const regex = new RegExp(
      /(?:(?:[a-zA-Z0-9])(?:[-.][a-zA-Z0-9])?)+(?:\.[a-z]{2,6})+$/
    )
    return regex.test(domainCheck)
  }
  return true
}

data(){
 return{
   domainName: ''
 }
}

validations:{
  domainName:{customDomainCheck}
}

Any further suggestions will be great!

Upvotes: 1

Related Questions