我们可以使用角度输入验证而无需形式

时间:2016-08-04 09:20:39

标签: javascript angularjs validation

有没有办法在没有表格的情况下使用角度输入验证。见角plunker。当我将<form name="myForm">更改为<div name="myForm">时,验证将不再有效。

HTML:

<form name="myForm">
  <label>
     User name:
     <input type="text" name="userName" ng-model="user.name" required>
  </label>
  <div role="alert">
    <span class="error" ng-show="myForm.userName.$error.required">
     Required!</span>
  </div>
  <label>
     Last name:
     <input type="text" name="lastName" ng-model="user.last" ng-minlength="3" ng-maxlength="10">
  </label>
  <div role="alert">
    <span class="error" ng-show="myForm.lastName.$error.minlength">Too short!</span>
    <span class="error" ng-show="myForm.lastName.$error.maxlength">Too long!</span>
  </div>
</form>

1 个答案:

答案 0 :(得分:3)

您需要拥有form指令,因为ngModel会搜索其控制器,以便自行注册并利用验证功能。

如果出于布局原因,您无法使用表单标记(嵌套的<form>标记无效),那么您可以使用ngForm指令来实现相同的效果:

<ng-form name="myForm">
  <label>
     User name:
     <input type="text" name="userName" ng-model="user.name" required>
  </label>
  <div role="alert">
    <span class="error" ng-show="myForm.userName.$error.required">
     Required!</span>
  </div>
  <label>
     Last name:
     <input type="text" name="lastName" ng-model="user.last"
     ng-minlength="3" ng-maxlength="10">
  </label>
  <div role="alert">
    <span class="error" ng-show="myForm.lastName.$error.minlength">
      Too short!</span>
    <span class="error" ng-show="myForm.lastName.$error.maxlength">
      Too long!</span>
  </div>
</ng-form>

演示: https://plnkr.co/edit/WlCqNBWtqiGerkQy0Wad?p=preview