简体   繁体   English

在表单进入Angular中的ng-submit之前验证表单

[英]Validate a form before it goes to ng-submit in Angular

I have a form which is wrapped like so: 我有一个像这样包裹的表格:

<form ng-submit="processForm()">
...
        <div class="btn-group" role="group" ng-hide=0>
          <button type="button" value="dog" class="btn btn-default" ng-click="formData.type='dog' ">Dog</button>
          <button type="button" value="cat" class="btn btn-default" ng-click="formData.type='cat' ">Cat</button>
        </div>
...

So one thing I have to do is run a quick check before submitting the form, to make sure that the person has clicked one of those 2 buttons. 因此,我需要做的一件事是在提交表单之前快速检查一下,以确保此人已点击其中一个按钮。 I can stick this code inside my processForm code, but I feel like it would be nicer to be able to just do a quick validation inside the html file and leave the processForm to not handle visually displaying this error and whatnot. 我可以将这段代码粘贴在我的processForm代码中,但我觉得能够在html文件中进行快速验证并让processForm无法直观地显示此错误等等会更好。 Is there a way or am I wrong? 有办法还是错了?

I would recommend using radio buttons for that. 我建议使用单选按钮。 Also there is an error variable given by angular. 还有一个由angular给出的错误变量。 With mixing these things and html5, you can simply create good validation for this. 通过混合这些东西和html5,您可以简单地为此创建良好的验证。 Without need to submit that to functions. 无需将其提交给函数。

    <form ng-submit="processForm()" name="form">
    ...
    <div class="input-group">
      <span class="input-group-addon">
          <input type="radio" name="type" ng-model="type" value="dog" required>  Dog <br/>
      </span>
      <span class="input-group-addon">
          <input type="radio" name="type" ng-model="type" value="cat" required>  Cat <br/>
      </span>
    </div>
    <div ng-show="form.name.$error.required">
    Please select one.
    </div>

Here is something about it. 是关于它的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM