Permalink
Browse files

Validate post contents on submission

chapter9-4
  • Loading branch information...
tmeasday committed Oct 15, 2014
1 parent c9af05e commit 9791d73b51d0ab5a95103d9c784032e051dd99f7
Showing with 37 additions and 2 deletions.
  1. +4 −2 client/templates/posts/post_submit.html
  2. +17 −0 client/templates/posts/post_submit.js
  3. +16 −0 lib/collections/posts.js
@@ -1,15 +1,17 @@
<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>
<div class="controls">
<input name="title" id="title" type="text" value="" placeholder="Name your post" class="form-control"/>
<span class="help-block">{{errorMessage 'title'}}</span>
</div>
</div>
<input type="submit" value="Submit" class="btn btn-primary"/>
@@ -1,3 +1,16 @@
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' : '';
}
});
Template.postSubmit.events({
'submit form': function(e) {
e.preventDefault();
@@ -7,6 +20,10 @@ Template.postSubmit.events({
title: $(e.target).find('[name=title]').val()
};
var errors = validatePost(post);
if (errors.title || errors.url)
return Session.set('postSubmitErrors', errors);
Meteor.call('postInsert', post, function(error, result) {
// display the error to the user and abort
if (error)
View
@@ -12,6 +12,18 @@ Posts.deny({
}
});
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;
}
Meteor.methods({
postInsert: function(postAttributes) {
check(this.userId, String);
@@ -20,6 +32,10 @@ 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 {

0 comments on commit 9791d73

Please sign in to comment.