【问题标题】:Implementing a form validation plugin with AngularJS with Django REST at the server side在服务器端使用 AngularJS 和 Django REST 实现表单验证插件
【发布时间】:2013-08-20 06:12:29
【问题描述】:

我现在正在使用 Angular 为 Django REST Framework 后端实现客户端。

为了在最短时间内启动并运行项目的 Alpha,我们决定直接使用服务器端验证。

Django rest 返回一个 JSON 字符串,字段和错误之间是一一对应的。

Django的这个特性可以让我在几分钟内用jQuery实现这样一个特性。

问题是如何使用 angular 来做到这一点?

代码示例:

表格:

<label for="uname">Login:</label>
                    <div class="inputUnit" name="email">
                        <input tpye="email" class="text" name="email" ng-model="formData.email">
                    </div>
<label for="password">password:</label>
                    <div class="inputUnit">
                        <input type="password" class="text" name="password" ng-model="formData.password">
                    </div>

如果两个字段都为空,来自服务器的 JSON 响应:

{"password": ["This field is required."], "email": ["This field is required."]}

如果密码丢失且电子邮件与正则表达式不匹配,则服务器的 JSON 响应:

{"password": ["This field is required."], "email": ["Enter a valid e-mail address."]}

实现通用组件以向用户显示这些错误的最佳做法是什么?

显示错误后所需的 HTML:

<label for="uname">Login:</label>
                    <div class="inputUnit" name="email">
                        <input tpye="email" class="text" name="email" ng-model="formData.email">
<label for="error">Email error here</lable>
                    </div>
<label for="password">password:</label>
                    <div class="inputUnit">
                        <input type="password" class="text" name="password" ng-model="formData.password">
<label for="error">Password error here</lable>
                    </div>

【问题讨论】:

  • 我想实现这样的原因:服务器端验证总是更强大更好。后端的一些规则可能会不时更改,这样它们会在前端自动更新
  • 看到您的控制器也很好,或者您将数据发布到服务器的任何地方。
  • 它是一个简单的控制器,它使用服务将表单数据提交给API端点,如果确实有错误,API返回json错误字符串

标签: javascript validation angularjs django-rest-framework


【解决方案1】:

在这里您可以找到我尝试使用指令https://github.com/9ci/angle-grinder/blob/c0211c885c561f8ec820b38d506135f4fb8b6dfb/app/scripts/modules/forms.coffee#L321 处理服务器端验证错误,希望它对您有用。

【讨论】:

  • 感谢您分享您的代码 Lucas,这是 var 的最佳答案。
猜你喜欢
  • 2013-04-16
  • 2012-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-06
  • 1970-01-01
  • 2014-04-06
  • 2012-09-06
相关资源
最近更新 更多