2014-11-20 45 views
0

我一直在試圖自己想象這個,但最終無法在很長時間過後。發現流星:將http://自動添加到輸入的URL

我目前正在關注Meteor.js的Discover Meteor Book。

我注意到提交沒有http://的帖子會鏈接到localhost:3000/submittedurl

我想讓流星在提交時自動將http://添加到網址。從邏輯上講,當方案包含在輸入字段中時,它不會添加http://

//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}); 
     }); 
    } 
}); 
+0

請準確,並解釋更多關於問題 – ajduke 2014-11-20 17:51:54

回答

0

那麼,其實這是一個簡單的javascript問題,不一定與流星有關。

舉例來說,這個問題的答案Prepending "http://" to a URL that doesn't already contain "http://"提供了一種方法:

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

,或者你可以看到不同的方法,其他的答案。我認爲JS-URI庫方法更安全。

所以我們可以說你具有與上述在源聲明的checkForProperURLPrefixAndFixIfNecessary(testUrl)功能,則可以更改

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

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

但是,一旦你通過探索流星書,完成這是學習流星的最佳方式,看看真棒https://github.com/aldeed/meteor-simple-schema包或只搜索架構驗證https://atmospherejs.com/爲更加健壯的方式檢查用戶輸入適當的類型和結構。

+0

此外,url方案可以有不同的上下文,如http,https,ftp,scp,mailto等,我寧願讓用戶知道通過顯示錯誤提示,而不是隻是繼續和*固定*輸入假設它是http。 – 2014-11-20 18:58:46

+0

非常感謝你Serkan Durusoy。我是一名設計師,嘗試學習網絡開發,以進一步提高我在網絡應用程序創作方面的知識和技能。我會盡力去解決這個問題! – 2014-11-21 11:01:46

+0

發現流星是一個很好的資源@SangYooKim和完成後,請確保您通讀官方http://docs.meteor.com – 2014-11-21 19:14:53