user5479362
user5479362

Reputation:

Distinguish between value invalid and value not given in Angular2 control

I have a control that should accept only numbers, and I want to give the user a hint why the control is marked red:

<label>Version</label>
<input name="version" #version="ngModel" required type="number" pInputText [(ngModel)]="item.version"/>
<small class="field-validation-error" [hidden]="version.valid">
  Not a number
</small>

The problem is, the message is shown when there's no value in the control. This is invalid, but I want to show 'Value is required' message then. I've tried:

    <small class="field-validation-error" [hidden]="version.value">
      Value is required
    </small>

but then, the 'Value is required' message is displayed event if the value is provided, but is not a numer.

How can I distinguish between value not give, and value given, but invalid, using ngModel binding?

Upvotes: 0

Views: 109

Answers (2)

soywod
soywod

Reputation: 4510

What about :

<label>Version</label>
<input name="version" #version="ngModel" pattern="[0-9]*" required type="number" pInputText [(ngModel)]="item.version"/>

<small class="field-validation-error" *ngIf="version.control.dirty && version.control.hasError('required')">
    Value is required
</small>

<small class="field-validation-error" *ngIf="version.control.dirty && version.control.hasError('pattern')">
    Not a number
</small>

Upvotes: 0

Herr Derb
Herr Derb

Reputation: 5357

I'd just go with

  <small class="field-validation-error" [hidden]="item.version.value">
      Value is required
    </small>

just check the real value instead the value of the input element

Upvotes: 0

Related Questions