javascriptangularjsng-showangular-ng-if

Show error if button clicked and input text empty AngularJs


I create a login page , I show error if user click in input text and let him empty

but I need to show error if user don't click in input text and click login button

My code :

<form ng-submit="userForm.$valid && submit()" name="userForm" novalidate>
   <div class="form-group" ng-class="{ 'has-error': userForm.login.$touched && userForm.login.$invalid }">
      <input type="text" name="login"  placeholder="اسم المستخدم" class="form-control" ng-model="MainCtrl.login" ng-minlength="5" ng-maxlength="10" required>
      <div class="help-block" ng-messages="userForm.login.$error" ng-if="userForm.login.$touched">
         <p ng-message="required">إسم المستخدم إجباري</p>
         <p ng-message="minlength">إسم المستخدم قصير</p>
         <p ng-message="maxlength">إسم المستخدم طويل</p>
      </div>
      <i class="fa fa-user"></i>
   </div>
   <div class="form-group" ng-class="{ 'has-error': userForm.pass.$touched && userForm.pass.$invalid }">
      <input type="password" name="pass" placeholder="كلمه السر" class="form-control" ng-model="MainCtrl.pass" ng-minlength="5" ng-maxlength="20" required>
      <div class="help-block" ng-messages="userForm.pass.$error" ng-if="userForm.pass.$touched">
         <p ng-message="required">كلمة السر اجبارية</p>
         <p ng-message="minlength">كلمة السر قصيرة</p>
         <p ng-message="maxlength">كلمة السر طويلة</p>
      </div>
      <i class="fa fa-lock"></i>
   </div>
   <div class="form-group">
      <button type="submit" class="log-btn">دخول</button>
   </div>
</form>

this is my code in plunker


Solution

  • You can us required="" on your input tag and userForm.$submitted on your error messages block:

    <div class="form-group" ng-class="{ 'has-error': (userForm.login.$touched && userForm.login.$invalid) ||  (userForm.$submitted && userForm.login.$invalid)}">
       <input type="text" name="login"  placeholder="اسم المستخدم" class="form-control" ng-model="MainCtrl.login" ng-minlength="5" ng-maxlength="10" required="">
       <div class="help-block" ng-messages="userForm.login.$error" ng-show="userForm.$submitted || userForm.login.$touched">
          <p ng-show="userForm.login.$error.required" ng-message="required">required error</p>
          <p ng-show="userForm.login.$error.minlength">minLength error</p>
          <p ng-show="userForm.login.$error.maxlength">maxLength error</p>
       </div>
       <i class="fa fa-user"></i>
    </div>
    

    DEMO