Browse Source

Commit 9-5: Validate post contents when editing.

Frederic G. MARAND 8 years ago
parent
commit
cc0e6c19f6

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

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

+ 20 - 1
client/templates/posts/post_edit.js

@@ -18,8 +18,13 @@ Template.postEdit.events({
       title: $(e.target).find('[name=title]').val()
     };
 
+    var errors = validatePost(postProperties);
+    if (errors.title || errors.url) {
+      Session.set('postEditErrors', errors);
+      return;
+    }
 
-    Posts.update(currentPostId, { $set: postProperties },function (error) {
+    Posts.update(currentPostId, { $set: postProperties }, function (error) {
       // Display the error to the user and abort.
       if (error) {
         return throwError(error.reason);
@@ -41,3 +46,17 @@ Template.postEdit.events({
 
   }
 });
+
+Template.postEdit.onCreated(function () {
+  Session.set('postEditErrors', {});
+});
+
+Template.postEdit.helpers({
+  errorMessage: function (field) {
+    return Session.get('postEditErrors')[field];
+  },
+
+  errorClass: function (field) {
+    return Session.get('postEditErrors')[field] ? 'has-error' : '';
+  }
+});

+ 1 - 1
client/templates/posts/post_submit.js

@@ -20,7 +20,7 @@ Template.postSubmit.events({
     if (errors.title || errors.url) {
       Session.set('postSubmitErrors', errors);
       // We return to abort the helper, not for anyone using the result.
-      return null;
+      return;
     }
 
     Meteor.call('postInsert', post, function (error, result) {

+ 10 - 0
lib/collections/posts.js

@@ -28,6 +28,16 @@ Posts.deny({
   }
 });
 
+Posts.deny({
+  // In a post edit, the update is performed by a $set modifier, with the same
+  // fields as the base inserted post: url and title, so we can pass it to
+  // the post validator as it currently stands.
+  update: function (userId, post, fieldNames, modifier) {
+    var errors = validatePost(modifier.$set);
+    return errors.title || errors.url;
+  }
+});
+
 // This is in lib/ instead of server/ for latency compensation.
 Meteor.methods({
   postInsert: function(postAttributes) {