【问题标题】:how to validate element is angular js?如何验证元素是 Angular js?
【发布时间】:2014-08-08 08:19:01
【问题描述】:

我从 json 对象创建一个视图。我现在可以采取行动,我需要在 keyup 事件和 blur 事件上有效元素。所以我用谷歌搜索并找到了这个教程 http://scotch.io/tutorials/javascript/angularjs-form-validation

我尝试在我的演示中实现这个,但是当我使用这个时:

<p ng-show="userForm.name.$invalid && !userForm.name.$pristine"
    class="help-block">`Your name is required.</p>

这打破了我的看法,如果没有表格,你能告诉我如何以角度验证事物吗?

这是我的小伙伴:http://plnkr.co/edit/we1QHuDuCOOR4tDAk6yv?p=preview

  <script>
    function Controller($scope) {
    $scope.outputs = {};
    $scope.inputs = [{
        type: "email",
        name: "email",
        required:true
    }, {
        type: "text",
        name: "name",
    }, {
        type: "number",
        name: "phonenumber",
    }, {
        type: "checkbox",
        name: "whant to check",
    },
    {
        type: "url",
        name: "server Url",
    }];

}
  </script>

【问题讨论】:

  • 如果没有表单,您将无法使用 Angular 的表单验证。您必须连接到 ng-change 或在控制器中使用 $watch
  • 你能改变我的 plunker 吗..举个例子..我可以改变形式吗?
  • 有什么方法可以在表单上更改此设置或其他验证方式吗?
  • @irani 你有什么解决办法

标签: javascript jquery angularjs validation


【解决方案1】:

解决办法是使用ng-formlike

        <div ng-switch="input.type" ng-form="myfrm">
            <div ng-switch-when="text">
                <input type="text" ng-model="outputs[input.name]"/>
            </div>
            <div ng-switch-when="email">
                <input type="email" ng-model="outputs[input.name]" name="input" ng-required="input.required">
                <span ng-if="myfrm.input.$invalid">Please enter a valid email</span>
            </div>
            <div ng-switch-when="number">
                <input type="number" ng-model="outputs[input.name]"/>
            </div>
            <div ng-switch-when="url">
                <input type="number" ng-model="outputs[input.name]"/>
            </div>
            <div ng-switch-when="checkbox">
                <input type="checkbox" ng-model="outputs[input.name]" ng-checked="outputs[input.name]" value="outputs[input.name]"/>
            </div>
        </div>

演示:Plunker

【讨论】:

  • 我需要在模糊以及向上和向下键上添加验证?
  • @user3665790 see plnkr.co/edit/JleucNFICr9OXl7mb4ch?p=preview - input in myfrm.input.$invalid 是输入字段的名称
  • 您给出了很好的解决方案,在编写之前出现..red 框有问题。当用户按下提交时,它应该到那时(但有提交按钮)。当用户输入一些东西时,它会给出输入或将焦点移动到另一个字段时无效的电子邮件或有效邮件
  • @user3665790 现在我没有更好的解决方案...但是如果您可以发布一个新问题,其他人可能会为您提供帮助(因为您将此答案标记为已接受更多人可能不会再花更多时间在这上面)
  • 问题是为什么我运行应用程序时显示红色边框。我需要当用户运行应用程序时它不显示。它仅在将焦点移动到另一个字段时显示
猜你喜欢
  • 2015-05-17
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多