Hello fellow Meteor developers. I am hoping a Meteor guru can please review my code below and verify if I am making proper use of return false
and event.preventDefault()
, especially in the context of form submission. The reason being, the Meteor docs use this approach:
// Prevent default form submit
return false;
While other tutorials use this approach:
event.preventDefault(); //prevent page reload
So I want to be sure that I am on the correct path before I proceed with the rest of my code.
Basically, my code gets the value of the username input and checks if the value exists in the database:
HTML
<template name="registration">
<p class="message {{#if message_defined}}display_element{{/if}}">{{message}}</p>
<form id="register_form">
<input type="text" name="username" placeholder="username">
</form>
</template>
JS
if (Meteor.isClient) {
// This code only runs on the client
Meteor.subscribe("users");
Template.registration.helpers({
message: function () {
return Session.get("message");
},
message_defined: function () {
return Session.equals("message", undefined) ? false : true;
}
});
Template.registration.events({
"submit #register_form": function (event) {
// This function is called when the registration form is submitted.
event.preventDefault(); // Correct usage?
var form_data = {
username: event.target.username.value,
};
if (!Match.test(form_data.username, String)) {
Session.set("message", "username must be a string");
return false; // Correct usage?
}
if (form_data.username.length < 6) {
Session.set("message", "username must be at least 6 characters");
return false; // Correct usage?
}
Meteor.call("check_username",form_data.username,function(error, result){
if (error) {
Session.set("message", error);
return false; // Correct usage?
}
if (result) {
Session.set("message", result);
return false; // Correct usage?
}
});
}
});
}
Meteor.methods({
check_username: function (username) {
// If user exists, return error.
var user = Meteor.users.findOne({username:username});
if (user) {
throw new Meteor.Error("username exists", "That username is already in use.");
}
return "username not found";
}
});
if (Meteor.isServer) {
Meteor.publish("users", function () {
return Meteor.users.find(); // This publishes everything - be careful!
});
}