Angular empty input validation fails with currency

Viewed 161

Consider an HTML input form with red error text that informs when field is empty. Notice it relies on ng-show=$error.required && $touched

<div class="form-group">
    <div class="input-group">
        <input id="qp-cargo-value" name="qpCargo" placeholder="$" type="text" 
               class="form-group" currency="229" data-ng-model="cargoValue" required>
    </div>
    <div class="rederrorlabel"
         ng-show="myform.qpCargo.$error.required && myform.qpCargo.$touched">
        Error - Cargo value is required
    </div>
</div>

It works fine for fields without the ccy attribute. But for inputs with ccy, when the input is empty the default value stored in angular is not null but $, which fails to trip the $error.required condition

Here is console output for the value as I enter and then delete values, confirming that it never gets set to null but rather to "$".

enter image description here

Is there anyway to retain the ccy formatting but somehow still use $error.requried in an input field?

1 Answers

the standard seems to be to have an input prepend for $ and only take in the amount not the symbol.

Bootstrap EX:

Bootstrap currency input

If you prefer to leave it the way it is, you can write a method that checks for a valid entry returning a bool and use it for the ng-show.

  public currencyValidation(): boolean {
    return myform.qpcargo.value.replace('$', "").length < 1;
  }
<div class="form-group">
    <div class="input-group">
        <input id="qp-cargo-value" name="qpCargo" placeholder="$" type="text" 
               class="form-group" currency="229" data-ng-model="cargoValue" required>
    </div>
    <div class="rederrorlabel"
         ng-show="currencyValidation() && myform.qpCargo.$touched">
        Error - Cargo value is required
    </div>
</div>

Related