0
votes

I've been trying to figure this on my own but ended up not being able to after many long hours.

I'm currently following the Discover Meteor Book for Meteor.js.

I noticed that submitting the post without the http:// would link the links to localhost:3000/submittedurl.

I want meteor to automatically add http:// to URLs when submitted. Logically, it wouldn't add the http:// when a scheme is included in the input field.

//post_submit.js

Template.postSubmit.created = 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();

        var post = {
            url: $(e.target).find('[name=url]').val(),
            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)
                return throwError(error.reason);

            // show this result but route anyway
            if (result.postExists)
                throwError('This link has already been posted');

            Router.go('postPage', {_id: result._id});
        });
    }
});
1
please be precise, and explain more about problem - ajduke

1 Answers

0
votes

Well, in fact this is a simple javascript question, not necessarily related to Meteor.

For example, the answer to this question Prepending "http://" to a URL that doesn't already contain "http://" provides a method:

checkForProperURLPrefixAndFixIfNecessary = function(testUrl) {
  var prefix = 'http://';
  if (testUrl.substr(0, prefix.length) !== prefix) {
    testUrl = prefix + testUrl;
  }
  return testUrl;
}

or you can see other answers for different methods. I think the JS-URI library approach is much safer.

So let's say you have the checkForProperURLPrefixAndFixIfNecessary(testUrl) function declared in your source as given above, then you can change

var post = {
  url: $(e.target).find('[name=url]').val(),
  title: $(e.target).find('[name=title]').val()
};

to

var post = {
  url: checkForProperURLPrefixAndFixIfNecessary( $(e.target).find('[name=url]').val() ),
  title: $(e.target).find('[name=title]').val()
};

But once you finish through the Discover Meteor book, which is the greatest way of learning Meteor, take a look at the awesome https://github.com/aldeed/meteor-simple-schema package or just search for schema or validation on https://atmospherejs.com/ for more robust ways of checking user input for proper type and structure.