0

new Vue({
  el: '#app',
  data: {
    email: ''
  },
  computed: {
    isEmailValid() {
      return '/^(([^<>()[\]\\.,;:\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,}))$/'.test(this.email)
    },
    isDisabled: function() {
      return !this.email || this.isEmailValid;
    }
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
  <p>
    <input class="input-mobile-email" type="text" placeholder="Your email" id="email" v-model="email" name="email" />
  </p>
  <button :disabled='isDisabled'>Send Form</button>
</div>

I am trying to disable the button until the email address is validated. So for that I have taken a computed property and written a function. And then I am trying to pass the function's name to isDisabled.

But there is an issue with the validation and the button doesn't get enabled, even if a correct email address is entered.

This is a jsfiddle where I tried the functionality https://jsfiddle.net/k69cr0sf/2/

1 Answer 1

4

There are two problems with your code

  1. A regex must not be enclosed in quotes ''

  2. Your isDisabled() function returns the wrong value, because it returns true if this.isEmailValid == true which is obviously wrong.

You can also simplify your logic, as your regex won't match an empty string. Thus your isDisabled() can simply return the negated result of the regex test, ie return !/.../.test(this.email)

new Vue({
  el: '#app',
  data: {
    email: ''
  },
  computed: {
    isDisabled: function() {
      return !/^(([^<>()[\]\\.,;:\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,}))$/.test(this.email)

    }
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
  <p>
    <input class="input-mobile-email" type="text" placeholder="Your email" id="email" v-model="email" name="email" />
  </p>
  <button :disabled='isDisabled'>Send Form</button>
</div>

PS: You can add external scripts also to your code snippets, if you click on Add External scripts and input the url. Thus for simple cases, there is typically no need to link to external jsfiddles and you can keep your questions self-contained.

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

Comments

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.