So, I have an input for the user to enter his username. The username is bound to the vue instance via v-model
.
I made this function in my controller to check if a username is unique or not (tested and it works):
/**
* @description
* GET /api/account/unique/username/:username
* Checks if new user signing up has a unique username
*/
module.exports.isUsernameUnique = function isUsernameUnique(req, res, next) {
const username = req.params.username;
if(!username) {
return res.status(400).send({ message: 'Username is missing.' });
}
personRepository.findPersonByUsername(username, (err, person) => {
if(person) {
return res.status(400).send({ message: 'Username has already been taken.' });
} else {
res.status(200).send({ unique: true });
}
});
};
In my vue script:
data: {
username: ''
},
methods: {
isUsernameUnique: function() {
var self = this;
var url = 'api/account/unique/username/' + self.username;
self.$http.get(url)
.then(function(res){
}, function(err){
});
}
}
If the username typed by the user is not unique, a span below the input should be displayed with an error message almost immediately. How do I accomplish this?
You can add one flag variable in your data() with initial value of false which will get true once the response from api gives result as username is unique.
Please take a look of below code change:
data: {
username: '',
isUniqueUserName: false
},
methods: {
isUsernameUnique: function() {
var self = this;
var url = 'api/account/unique/username/' + self.username;
self.$http.get(url)
.then(function(res){
if(res.unique) this.isUniqueUserName = true;
}, function(err){
});
}
}
In your span add this
<span v-if="!isUniqueUserName ">User Name is Not Unique</span>