Hi everybody! I am a beginner at Vue.js 2. I would like to validate my registration form before submitting it. How can I do it?
<form>
<div class="form-text">
<p class="control has-icon has-icon-right">
<input
name="email"
type="text"
placeholder="Email"
class="form-control">
</p>
</div>
<div class="form-text">
<p class="control has-icon has-icon-right">
<input
name="phone"
type="text"
placeholder="Phone"
class="form-control">
</p>
</div>
<div class="form-text">
<span class="custom-dropdown custom-dropdown--white">
<select class="custom-dropdown__select custom-dropdown__select--white" v-on:change="selectCountry" v-model="country">
<option value="" disabled selected>Choose your country</option>
<option v-for="country in countries" :value="country.dial_code" :key="country.code">{{country.name}}</option>
</select>
<p class="selectPlaceholder" v-show="this.showCountryPlaceholder">Choose your country</p>
</span>
</div>
<div class="form-text">
<input
name="password"
class="form-control"
type="text"
placeholder="Password">
</div>
<div class="form-button">
<button class="btn btn-default" id="submit" type="submit">Sign up
<i class="fas fa-arrow-right"></i>
</button>
</div>
</form>
Most important call you need to, except if it's pure AJAX, is event.preventDefault() to stop the default form behaviour.
One simple way of doing it is
isValid(event) {
event.preventDefault()
let valid = true
['firstname', 'lastname', 'email'].forEach(name => {
if (this.$refs[name].value === '')
valid = false
})
return valid
}
You could expand it to look at type to validate email etc and give user feedback.
I realize this is more basic JavaScript than actual Vue. So feel free to provide an example so I know what kind of context it is.
Vladimir Kyuchukov
Web/Mobile Dev
Please use the original documentation of Vue. It is pretty well written. vuejs.org/v2/cookbook/form-validation.html