I am trying to validate the Username field in Vue using regex. I have a key down event on the textbox and on each key down the below method is called
userNameValidation(event) {
if (!event.key.match(/^[a-zA-Z0-9._] $/)) {
event.preventDefault();
}
}
The issue with this regex is that it allows .
and _
at the start which I do not want.
I want the username to contain the alphabets, numbers, .
and _
and it should start with the alphabet.
CodePudding user response:
Use two characters sets, one at the start matching [a-z]
one time, then the more permissive one you have matching zero or more times.
/^[a-z][a-z0-9._]*$/i
CodePudding user response:
Instead of validating on key press event. You can validate the username field on blur to match the whole regex in a single go.
Demo :
new Vue({
el: '#app',
data: {
username: null
},
methods: {
validateUserName() {
if (!this.username.match(/^[a-z][a-z0-9._]*$/i)) {
console.log('validation not passed!');
event.stopPropagation();
} else {
console.log('validation passed!');
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
User Name : <input type="text" v-model="username" @blur="validateUserName"/>
</div>