Angular Form Validation: $error.required set even when ng-required=false with custom input directive

Issue

I have Custom input component with validation with ngMessages,FormController and ng-required:

<div class="col-sm-9 col-xs-12">
    <input
      id="{{$ctrl.fieldName}}"
      name="{{$ctrl.fieldName}}"
      class="form-control"
      type="text"
      minlength="{{$ctrl.minLength}}"
      maxlength="{{$ctrl.maxLength}}"
      ng-required="{{$ctrl.isRequired === 'true'}}"
      ng-model="$ctrl.value"
      ng-change="$ctrl.form.$submitted = false;"
  >
    <div 
      ng-messages="$ctrl.form[$ctrl.fieldName].$error"
      ng-if="$ctrl.form.$submitted"
    >
      <span class="help-block" ng-message="required">
        Field is required
      </span>
      <span class="help-block" ng-message="minlength">
        Minimum length of field: {{$ctrl.minLength}}
      </span>
      <span class="help-block" ng-message="maxlength">
        Maximum length of field: {{$ctrl.maxLength}}
      </span>
    </div>
  </div>

Which is used in this way:

<act-text-field 
  form="heroAddForm" 
  field-name="name" 
  min-length="3" 
  max-length="15" 
  is-required="true" 
  errors="$ctrl.errors.name" 
  ng-model="$ctrl.hero.name">
</act-text-field>

What I want to achieve is validation fires when user clicks submit button. And it works, validation fires also for required field name, but also for field description which is not required:

<act-text-field 
  form="heroAddForm" 
  field-name="description" 
  max-length="50" 
  is-required="false" 
  errors="$ctrl.errors.description" 
  ng-model="$ctrl.hero.description"
></act-text-field>

Also for this field validation messages are visible, although field description is valid, cause I add class has-error to invalid fields:

<div class="form-group"
  ng-class="{'has-error': $ctrl.form.$submitted && (!$ctrl.form[$ctrl.fieldName].$valid)}" 
>
<!-- rest of code -->

You can easily reproduced this wrong behaviour in my Plunker: Custom input demo app with validation states (I know it has other mistakes). I think ng-message="required" should not be visible, because field description is not required. I know I can add some ng-ifs to code to by-pass it, but I think I make a mistake somewhere which I can’t see. Do you see where I made a mistake? Thank you in advance for every help.

Solution

I found a solution, again I forgot to include ngMessages. Without it, my code went crazy, I apologize for wasting your time 🙂

Answered By – Radek Anuszewski

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.