1. ホーム
  2. angularjs

[解決済み] AngularJS <input> validation with no enclosing <form>

2022-12-18 19:37:38

Question

Is it possible in Angular to validate a single, isolated <input> in a similar way the forms are validated? I'm thinking about something like this:

<div class="form-group">
    <input name="myInput" type="text" class="form-control" ng-model="bindTo" ng-maxlength="5">
    <span class="error" ng-show="myInput.$error.maxlength">Too long!</span>
</div>

The example above doesn't work. Enclosing it in a <form> and replacing ng-show with ng-show="myForm.myInput.$error.maxlength" helps.

Is it possible to do this without using <form> ?

How to solved?

You may use the ng-form angular directive ( see docs here ) を使って、HTML フォームの外でも何でもグループ化することができます。そして、angular FormController を利用することができます。

<div class="form-group" ng-form name="myForm">
    <input name="myInput" type="text" class="form-control" ng-model="bindTo" ng-maxlength="5">
    <span class="error" ng-show="myForm.myInput.$error.maxlength">Too long!</span>
</div>