停止使用AngularJS以表单发布html标签 [英] Stop posting html tags in form using AngularJS
问题描述
我有一个表单,我希望用户不能输入html标签或脚本并在angularjs中提交表单.
为此,我正在使用$sanitize
,但是它不起作用.
I have a form, In which I want user couldn't enter html tags or script and submit form in angularjs.
for this I'm using $sanitize
but it's not working.
这是我的表格
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular-sanitize.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body ng-app="birthdayToDo" ng-controller="main">
<h1>Hello Plunker!</h1>
<form name="testForm" ng-submit="submitForm(testForm.$valid)" novalidate>
<input type="text" name="name" ng-model="testText"/>
<p ng-show="testForm.name.$dirty && testForm.name.$invalid && testForm.submitted" class="error">
Invalid Input
</p>
<input type="submit" value="Save"/>
</form>
</body>
</html>
他输入无效的输入后,就会显示一条错误消息. 我正在使用这个概念
as soon as he enter invalid input, It shows an error message. I'm using this concept
$scope.SanitizeDemo=function() {
return $sce.trustAsHtml($scope.testText);
};
推荐答案
我认为您正在以错误的方式进行操作.在angularjs和后端中使用白名单正则表达式来验证输入.
I think you are going about this the wrong way. Use a whitelist regular expression in both angularjs as well as your backend to validate the input.
为了安全起见,最佳做法是为每个字段都使用一个正则表达式,该正则表达式仅允许某些有效输入.一个简单的名称是/^[a-z ,.'-]+$/i
.这将在服务器端进行,以防止发送任何无效的数据.也可以将其放置在客户端以进行验证.
For security, best practice is for each field to have a regular expression which will only allow certain valid input. A simple one for name would be /^[a-z ,.'-]+$/i
. This would be on the server side to prevent any data being sent that was not valid. This could also be placed on the client side to also validate.
默认情况下,当使用{{}}
防止XSS时,Angularjs会对输出进行编码,因此<b>abs</b>
将按原样显示,从安全的角度来看,这是您想要的,以防止第三方脚本在您的页面上执行.
By default Angularjs encodes output when using {{}}
to protect against XSS, so <b>abs</b>
will appear as is and this is what you want from a security point of view to prevent third party script from executing on your page.
在某些情况下,您可能希望允许html的输出并安全地允许它输出,但是在这种情况下,您可以将ng-bind-html
与ng-sanitize
一起使用,而无需直接使用$sce
.
In some cases you may want to allow output of html and allow it safely but in which case you can use ng-bind-html
with ng-sanitize
and don't need to use $sce
directly.
这篇关于停止使用AngularJS以表单发布html标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!