I have a form with in between the <template>
tags
<form>
<div class="form-group">
<label for="email">Email address</label>
<input v-model="email" for="email" type="email" class="form-control" placeholder="Enter email" required>
</div>
<div class="form-group">
<label for="name">Name</label>
<input v-model="name" for="name" type="text" class="form-control" placeholder="Name" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input v-model="password" type="password" class="form-control" for="password" placeholder="Password" required>
</div>
<div class="form-group">
<label for="Confirm">Confirm Password</label>
<input v-model="confirmPassword" type="password" class="form-control" for="Confirm" placeholder="Confirm Password" required>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1" required>
<label class="form-check-label" for="exampleCheck1">I agree to the terms and conditions</label>
</div>
<button v-on:click="Submit" type="submit" class="btn btn-primary">Submit</button>
I have v-model
which is updating the data
in the script
section in real time.
The data
:
data(){
return{
email: undefined,
password: undefined,
confirmPassword: undefined,
name: undefined
}
},
I expect undefined
to be updated by v-model
On clicking The form's button the Submit
method is called.
The Submit
method:
prints empty if input is empty
and passed
if the input is not empty (works as expected)
prints empty
if input is empty and empty
even if both the inputs are filled (not as expected)
methods:{
Submit(){
console.log(this.email); //prints the data in entered in the form correctly
console.log(this.name); //prints the data in entered in the form correctly
console.log(this.password); //prints the data in entered in the form correctly
console.log(this.confirmPassword); //prints the data in entered in the form correctly
if(this.email == undefined){ console.log('Empty')} //prints empty if input is `empty` and `passed` if the input is not empty (works as expected)
else{console.log('passed')};
if(this.email || this.name == undefined){console.log('Empty');} //prints `empty` if input is empty and `empty` even if both the inputs are filled (not as expected)
else {console.log('Passed');}
}
}
The OR || operator will return true if at least one of the operands is true.
In your second if statement it checks this.email
has a truthy value, OR this.name
is undefined
, then it will return true. In your scenario, if both the values are filled, then it will simply be true.
You want to use the AND && operator to check if both conditions are truthy.
Alternatively, for vue, you can use a validation library like Vuelidate or VeeValidate.