如何在Vue.js中基于长度检查实现密码与确认密码的按钮禁用控制?
Absolutely, checking the field lengths is a great approach to resolve this issue! Your current setup has a problem where the button enables too early—let's adjust the logic to ensure it only activates when both password fields are valid, have matching lengths, and identical values.
Here's how to modify your button code:
<button type="submit" :disabled=" !user.password || !user.confirmPassword || !$v.user.password.valid || !$v.user.confirmPassword.valid || user.password.length !== user.confirmPassword.length || user.password !== user.confirmPassword " > Submit </button>
Let’s break down each part of the disabled condition to make sure you understand why this works:
!user.password || !user.confirmPassword: Keeps the button disabled if either field is empty (prevents unnecessary checks on undefined/empty values)!$v.user.password.valid: Ensures your password field passes all configured Vuelidate rules (like minimum length, required characters, etc.)!$v.user.confirmPassword.valid: Makes sure the confirm password field also passes its validation rulesuser.password.length !== user.confirmPassword.length: Forces the two fields to have exactly the same number of characters—this is the key check you wanted to adduser.password !== user.confirmPassword: Confirms the actual content of both fields is identical (even if lengths match, we need to ensure the values are the same)
A Quick Note on Vuelidate's sameAs Rule
If your sameAsPassword rule in Vuelidate is supposed to check for full value matching, it might not be configured correctly (which is why your original code was enabling the button on partial matches). The above code adds explicit checks for length and value equality to bypass any potential issues with that rule, but if you want to rely on Vuelidate fully, you can verify that your sameAs rule is set up like this (in your validation schema):
validations: { user: { password: { // your existing password rules (required, minLength, etc.) }, confirmPassword: { sameAsPassword: sameAs('password') } } }
Even with a correctly configured sameAs rule, adding the length check is still a good user experience touch—it gives users immediate feedback that their inputs don’t match before they finish typing.
内容的提问来源于stack exchange,提问作者T dhanunjay

