[英]Discover Meteor: Add http:// automatically to inputted URL
我一直在尝试自己解决这个问题,但最终却无法在很长的时间内工作。
我目前正在关注Meteor.js的“发现流星”书。
我注意到提交不带http://
的帖子会将链接链接到localhost:3000/submittedurl
。
我希望流星在提交时自动将http://
添加到URL。 从逻辑上讲,当输入字段中包含方案时,它不会添加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});
});
}
});
好吧,实际上这是一个简单的javascript问题,不一定与Meteor有关。
例如,对于以下问题的答案,在不包含“ http://”的URL前面加“ http://”可提供一种方法:
checkForProperURLPrefixAndFixIfNecessary = function(testUrl) {
var prefix = 'http://';
if (testUrl.substr(0, prefix.length) !== prefix) {
testUrl = prefix + testUrl;
}
return testUrl;
}
或者您可以查看其他答案以了解不同的方法。 我认为JS-URI库方法要安全得多。
因此,假设您已经在源代码中声明了checkForProperURLPrefixAndFixIfNecessary(testUrl)
函数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/,以提供更强大的方法来检查用户输入的正确类型和结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.