9

I am using angular form validation using the below code

<form ng-app="" ng-controller="validateCtrl" name="myForm" novalidate>
  <p>Username:<br>
   <input type="text" name="user" ng-model="user" required>
     <span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
         <span ng-show="myForm.user.$error.required">Username is required.</span>
      </span>
 </p>
</form>

But if i want to use like this:

<div ng-app="" ng-controller="validateCtrl" name="myForm" novalidate>
  <p>Username:<br>
   <input type="text" name="user" ng-model="user" required>
     <span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
         <span ng-show="myForm.user.$error.required">Username is required.</span>
      </span>
 </p>
</div>

But this is not working. Is there is any way to do this work? without using any other libraries.

jsfiddle:link

2 Answers 2

14

You can use the ngForm directive (here) in order to enable the $pristine, $dirty, $valid, $invalid services within it:

just define it this way:

<div ng-app="" ng-controller="validateCtrl" name="myForm" novalidate ng-form>

Here an example:

http://jsfiddle.net/s5efjzue/

Sign up to request clarification or add additional context in comments.

Comments

-1

Why not wrap the form in a div? This might achieve what you're looking for.

<div ng-app="" ng-controller="validateCtrl">
  <form name="myForm" novalidate>
    <p>Username:<br>
     <input type="text" name="user" ng-model="user" required>
       <span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
           <span ng-show="myForm.user.$error.required">Username is required.</span>
        </span>
   </p>
  </form>
</div>

Comments