我现在正在为 Django REST Framework 后端使用 Angular 实现客户端。
为了让项目的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>
最佳答案
在这里您可以找到我尝试使用指令 https://github.com/9ci/angle-grinder/blob/c0211c885c561f8ec820b38d506135f4fb8b6dfb/app/scripts/modules/forms.coffee#L321 来处理服务器端验证错误的尝试希望对您有用。
关于javascript - 在服务器端使用带有 Django REST 的 AngularJS 实现表单验证插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18297008/