Vue Js Name Validation
Vue Js Validate Name: In Vue.js, you can validate a name using a form input field by implementing a custom validation method. The process involves creating a custom rule for the name field, which checks whether the input is valid or not.In this tutorial we will learn how to validate name(First Name and Last Name).




Thanks for your feedback!
Your contributions will help us to improve service.
How to Validate Name (first name and last name) in Vue Js?
This is a form in Vue.js that implements client-side form validation. When the user submits the form, the validateForm
method is called, which performs validation on the first name and last name inputs. If the inputs are not valid, error messages are displayed next to the inputs.
The form input values are bound to the firstName
and lastName
data properties using the v-model
directive. The validateForm
method uses a combination of checks (e.g. if the input is empty, if the input is less than 2 characters, or if the input contains anything other than letters) to determine if the inputs are valid or not. If the inputs are not valid, the relevant error message is added to the errors
object.
The error messages are displayed using the v-if
directive. If the relevant error property (e.g. errors.firstName
) exists, the error message is displayed. If the inputs are valid, no error messages are displayed.
Validate first name and last name in Vue.js | Example
<div id="app">
<form @submit.prevent="validateForm">
<div>
<label for="first-name">First Name:</label>
<input type="text" id="first-name" v-model="firstName" />
<pre v-if="errors.firstName" class="error">{{ errors.firstName }}</pre>
</div>
<br>
<div>
<label for="last-name">Last Name:</label>
<input type="text" id="last-name" v-model="lastName" />
<pre v-if="errors.lastName" class="error">{{ errors.lastName }}</pre>
</div>
<button type="submit">Submit</button>
</form>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
firstName: '',
lastName: '',
errors: {}
};
},
methods: {
validateForm() {
this.errors = {};
if (!this.firstName) {
this.errors.firstName = 'First name is required';
} else if (this.firstName.length < 2) {
this.errors.firstName = 'First name must be at least 2 characters long';
} else if (!/^[a-zA-Z]+$/.test(this.firstName)) {
this.errors.firstName = 'First name can only contain letters';
}
if (!this.lastName) {
this.errors.lastName = 'Last name is required';
} else if (this.lastName.length < 2) {
this.errors.lastName = 'Last name must be at least 2 characters long';
} else if (!/^[a-zA-Z]+$/.test(this.lastName)) {
this.errors.lastName = 'Last name can only contain letters';
}
}
}
})
</script>