Mouss Mouss - 3 months ago 192
AngularJS Question

Can we use angular input validation without form

Is there a way to use angular input validation without form. See angular plunker. When I change

<form name="myForm">
by
<div name="myForm">
the validation does not work anymore.

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>

Answer

You need to have form directive because ngModel searches its controller in order to register itself and leverage validation capabilities.

If for layout reasons you can't have form tag (nested <form> tags are invalid) then you can use ngForm directive to achieve the same effect:

<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>

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

Comments