Search code examples
javascriptvue.jsemail-validation

Vue email validation is not returning true


I am really new to Vue and for this project I am using email validation followed by reg on VUE Script Data. When I print out the console.log(this.reg.test(this.email)) , while the user is filling the email input field, it validates correctly as true or false. NEXT button stays disable for both true and false case. Can we make the button enable, once the console.log(this.reg.test(this.email)) is true.

View

<div id="app">
  <h2>Todos:</h2>
  <input type="email" v-model="email" placeholder="enter email email address"/>
  <button v-bind:disabled="isDisableComputed">NEXT</button>
</div>

Script

new Vue({
  el: "#app",
  data: {
    email: '',
    reg: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,24}))$/
  },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    }
  },
  
  computed: {
      isDisableComputed() {
      if(this.reg.test(this.email) == 'true'){
        console.log(this.reg.test(this.email));
        return false;

      }
      else{
        console.log(this.reg.test(this.email));
        return true;
      }

    },
    
   }

})

Below is my code uploaded on JSFIDDLE

https://jsfiddle.net/ujjumaki/9es2dLfz/6/


Solution

  • Look into MDN: RegExp, RegExp.test return boolean, not one string. So this.reg.test(this.email) == 'true' will be always false.

    let regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,24}))$/
    
    console.log("regex.test('test@test.com')      ==> ", regex.test('test@test.com'))
    console.log("regex.test('test@test.com')=='true'  ==> ", regex.test('test@test.com') == 'true')
    console.log("regex.test('test@test.com')      ==> ", regex.test('test@test@.com'))
    console.log("regex.test('test@test@.com')=='true'  ==> ", regex.test('test@test@.com') == 'true')

    So uses return !this.reg.test(this.email) instead like the computed property=isDisableComputed in below snippet.

    new Vue({
      el: "#app",
      data () {
        return {
          email: '',
          reg: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,24}))$/
        }
      },
      methods: {
        toggle: function(todo){
            todo.done = !todo.done
        }
      },
      computed: {
        isDisableComputed() {
            return !this.reg.test(this.email)
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <h2>Todos:</h2>
      <input type="email" v-model="email" placeholder="enter email email address"/>
      <button :disabled="isDisableComputed">NEXT ({{isDisableComputed}})</button>
    </div>