Browse Source

Commit 9-4: Validate post contents on submission.

Frederic G. MARAND 9 years ago
parent
commit
cf30adb427

+ 1 - 0
.jshintrc

@@ -139,6 +139,7 @@
       // - Helpers
       "ownsDocument": true,
       "throwError": true,
+      "validatePost": true,
 
 
       // - Fictive global just for the last comma

+ 4 - 2
client/templates/posts/post_submit.html

@@ -1,14 +1,16 @@
 <template name="postSubmit">
   <form class="main form page">
-    <div class="form-group">
+    <div class="form-group {{ errorClass 'url' }}">
       <label class="control-label" for="url">URL</label>
       <div class="controls">
         <input name="url" id="url" type="text" value="" placeholder="Your URL" class="form-control" />
+        <span class="help-block">{{ errorMessage 'url' }}</span>
       </div>
     </div>
-    <div class="form-group">
+    <div class="form-group {{ errorClass 'title' }}">
       <label class="control-label" for="title">Title</label>
       <input name="title" id="title" type="text" value="" placeholder="Name your post" class="form-control" />
+      <span class="help-block">{{ errorMessage 'title' }}</span>
     </div>
     <input type="submit" value="Submit" class="btn btn-primary" />
   </form>

+ 21 - 0
client/templates/posts/post_submit.js

@@ -16,6 +16,13 @@ Template.postSubmit.events({
       title: $(e.target).find('[name=title]').val()
     };
 
+    var errors = validatePost(post);
+    if (errors.title || errors.url) {
+      Session.set('postSubmitErrors', errors);
+      // We return to abort the helper, not for anyone using the result.
+      return null;
+    }
+
     Meteor.call('postInsert', post, function (error, result) {
       // Display the error to the user and abort.
       if (error) {
@@ -29,3 +36,17 @@ Template.postSubmit.events({
     });
   }
 });
+
+Template.postSubmit.onCreated(function () {
+  Session.set('postSubmitErrors', {});
+});
+
+Template.postSubmit.helpers({
+  errorMessage: function (field) {
+    return Session.get('postSubmitErrors')[field];
+  },
+
+  errorClass: function (field) {
+    return Session.get('postSubmitErrors')[field] ? 'has-error' : '';
+  }
+});

+ 18 - 0
lib/collections/posts.js

@@ -38,6 +38,12 @@ Meteor.methods({
       url: String
     });
 
+    var errors = validatePost(postAttributes);
+    if (errors.title || errors.url) {
+      throw new Meteor.Error('invalid-post',
+        "You must set a title and URL for your post");
+    }
+
     var postWithSameLink = Posts.findOne({ url: postAttributes.url });
     if (postWithSameLink) {
       // Return to skip the insert.
@@ -59,3 +65,15 @@ Meteor.methods({
     };
   }
 });
+
+validatePost = function (post) {
+  var errors = {};
+  if (!post.title) {
+    errors.title = "Please fill in a headline";
+  }
+  if (!post.url) {
+    errors.url = "Please fill in a URL";
+  }
+
+  return errors;
+};