Conditionally Disable Input Elements in Vue.js
- Estimated read time: 4 min read
- Written by Chad Campbell on May 25th 2017
Vue.js provides a rich template syntax that empowers you to create a dynamic user experience. At runtime, there are situations where you may want to conditionally disable input elements. For example, many apps let a user change their password. In that situation, a user first enters their new password. Then, they have to confirm that password. This is usually seen in a screen that looks something like this.
On a screen like this, you may want to disable the "confirm password" field until a user enters a value in the new password field. To do that, you need to bind to the
The code above comes from the demo associated with this blog post. If you look at the code in that demo, you'll see a data property named
This expression examines the length of the
newPassword entered by the user. If the user has entered anything for their new password, this expresion will return
false. This has the impact of enabling the password confirmation field. If the expression returns
true, the input element will be disabled. While this expression is compact, it's also not very powerful. This is where a user-defined function can help.
Conditionally Disabling Input Element via User-Defined Functions
You may want to execute more logic before deciding whether to enable or disable an input element. For example, in the form above, you may want to verify that the "new password" field meets multiple requirements. You may want to ensure that the password exceeds a minimum number of characters. You may also want to ensure that at least one number is included in the password. Once all of the requirements are met, then the confirm password field can become enabled. When you need to use more logic, you can call a user-defined method in your template like this:
doesPasswordMeetRequirements exists in the Vue instance's
methods object. If you look in the demo code, you'll see that method defined like this:
This function expands on the original requirement and includes a regular expression to check for a number. If your requirements grow, your users may need help generating a new password. You may want to consider directing the user to a password generator. Still, I hope this post helps you understand how to conditionally disable input elements in Vue.js. If you want to learn more about Vue.js, I hope you'll check out my Vue.js training course on Pluralsight. If you don't have a Pluralsight subscription, I'd like to offer you a free trial.
If there are other Vue.js topics you're interested in, please mention them in the comments below. Thank you for reading.