Vue Js Radio Button Validation: In Vue.js, the v-model
directive is used to bind the radio buttons; this directive can be used to bind the selected option to a data property, which can then be used for validation. When creating a group of radio buttons, each button should have the same v-model
binding and a unique value
attribute. This will bind the selected option’s value to the data property, and the value
attribute will determine the value of the data property when the radio button is selected. When a form is submitted, the radio button validation rule can check if the bound data property has a value (i.e., if one of the radio buttons has been selected). Here in this example, we will learn how to validate a radio button in Vue JS.
How to validate radio buttons in Vue Js?
In this example, the validateForm
method checks if the selectedValue
data property is empty, and if it is, it shows the message “Please select an option” and returns false, which prevents the form from submitting. If the selectedValue
data property is not empty, it returns true, which allows the form to submit. This ensures that the form only submits if a valid option has been selected, and provides a helpful reminder to the user if they forget to select an option
Vue Js Radio Button Validation | Example
<div id="app">
<form @submit.prevent="validateForm">
<label>Select Option:</label>
<div v-for='(option,index) in options'>
<input type="radio" :id="index" v-model="selectedValue" :value="option">{{option}}
</div>
<br><br>
<button type="submit" @click="validateForm">submit</button>
</form>
<pre>Get Selected Value: {{selectedValue}}</pre>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
options: ['Apple', 'Google', 'Microsoft', 'Meta', 'HCL', 'Wipro', 'Tata'],
selectedValue: '',
}
},
methods: {
validateForm() {
if (!this.selectedValue) {
alert('please select an option');
return false;
}
alert('Form Submitted')
return true;
}
}
});
</script>