[SOLVED] Check if username exists and displaying error if it does on client-side

I’m in the middle of making a signup flow and I have a second step after users have signed up with email and password that asks for a username and display name (eg. real name) for the username I want to check if it already exists before the user can proceed. This is what I have so far (in lib/):

 validateOnboarding = function(userAttributes) {

	var errors = {};

	// username
	if(!userAttributes.profile.username) {
		errors.username = "Please specify a unique username.";
	}

	if(userAttributes.profile.username) {

		// check that username is unique
		Meteor.call('isUsernameAvailable', userAttributes.profile.username, function(error, result) {

			if(result) {
				errors.username = "This username already exists. Try another one.";
				console.log('username already in use');
			}
		});
	}

	// display name
	if(!userAttributes.profile.name) {
		errors.name = "Please specify a display name.";
	}

	return errors;
};

Basically just validating the input fields. I’ve understood as much that I need to do this asynchronous, but can’t figure out how to do it. Any suggestions? The method isUsernameAvailable looks like this:

isUsernameAvailable: function(username) {
		check(username, String);

		var userExistsId = Meteor.users.findOne({"profile.username": username}, {
			fields: {
				'_id': 1
			}
		});

		// If exists
		if(userExistsId && userExistsId._id!=Meteor.userId()) {
			return {
				_id: userExistsId
			};
		}
	},
1 Like

Try to call isUsernameAvailable on blur event of input.

1 Like

That worked perfectly @none! Thanks so much! :slight_smile:

1 Like

I’m just curious - how does this work? Why does the blur event register the callback?

1 Like