Created
April 18, 2020 23:32
-
-
Save fontzter/4ff0f6b553b071217ae837bbc074dabb to your computer and use it in GitHub Desktop.
Vuetify Password field with validation and hint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<v-text-field | |
:append-icon="show ? 'mdi-eye' : 'mdi-eye-off'" | |
:type="show ? 'text' : 'password'" | |
:rules="[validatePassword]" | |
:hint="hint" | |
persistent-hint | |
v-bind="mergedAttrs" | |
v-on="$listeners" | |
@click:append="show = !show" | |
/> | |
</template> | |
<script> | |
const hasLower = str => str !== str.toUpperCase() | |
const hasUpper = str => str !== str.toLowerCase() | |
const hasNumber = str => new RegExp(/\d+/).test(str) | |
const hasSpace = str => new RegExp(/[\s]+/).test(str) | |
const hasSymbol = str => | |
new RegExp(/[`~\!@#\$%\^\&\*\(\)\-_\=\+\[\{\}\]\\\|;:'",<.>\/\?€£¥₹]+/).test( | |
str | |
) | |
export default { | |
name: 'PasswordInput', | |
props: { | |
min: { type: [String, Number], default: 8 }, | |
max: { type: [String, Number], default: 100 }, | |
requireLowercase: { type: Boolean, default: true }, | |
requireUppercase: { type: Boolean, default: true }, | |
requireNumber: { type: Boolean, default: true }, | |
requireSymbol: { type: Boolean, default: true }, | |
allowSpaces: { type: Boolean, default: true }, | |
}, | |
data() { | |
return { | |
show: false, | |
} | |
}, | |
computed: { | |
hint() { | |
const required = ['Lowercase', 'Uppercase', 'Number', 'Symbol'] | |
.filter(req => this[`require${req}`]) | |
.map(req => req.toLowerCase()) | |
.reduce((acc, req, idx, arr) => { | |
if (idx === 0) return ` with at least one ${req}` | |
if (idx === arr.length - 1) return `${acc} and ${req}` | |
return `${acc}, ${req}` | |
}, '') | |
return `Min ${this.min} chars${required}` | |
}, | |
mergedAttrs() { | |
return Object.assign({}, this.$attrs, {}) | |
}, | |
}, | |
methods: { | |
validatePassword(password) { | |
if (!password) return 'Password is required' | |
if (password.length < this.min) | |
return `Must be at least ${this.min} characters` | |
if (password.length > this.max) | |
return `Must be less than ${this.max} characters` | |
if (this.requireLowercase && !hasLower(password)) | |
return 'Must contain a lowercase letter' | |
if (this.requireUppercase && !hasUpper(password)) | |
return 'Must contain an uppercase letter' | |
if (this.requireNumber && !hasNumber(password)) | |
return 'Must contain a number' | |
if (this.requireSymbol && !hasSymbol(password)) | |
return 'Must contain a special character' | |
if (!this.allowSpaces && hasSpace(password)) | |
return 'Cannot contain spaces' | |
return true | |
}, | |
}, | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment