简体   繁体   中英

How to disable button until email validated in Vuejs?

 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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM