Alex Beugnet
Alex Beugnet

Reputation: 4071

Angular2 pattern validator on Input

I'm trying to setup a pattern validator with the following regex :

Try Regex here

That should allow me to get 1 to 3 digits, and then a decimal part of maximum 2 digits, and that should allow empty values as well.

The problem is that either my input is of type text and the validator is rejecting my input (any input since it's not considered as a digit I believe); or the input is of type number and without step="any" my input value is rejected if I have a decimal input (while the regex seems to be working on simpler values), and with step="any" it seems my regex is not working at all, allowing whatever value because of the step.

<form (ngSubmit)="onSubmit()" #bottleUpdatePriceForm="ngForm" >

    <div class="form-group" *ngFor="let bottle of bottleArrayToUpdate; let i = index">
      <label for="bottlePrice">{{bottle.name}} : </label>
      <input type="number" class="form-control" name="bottlePrice" autocomplete="off" step="any"
      [pattern]="pricePattern"
      [(ngModel)]="bottleArrayToUpdate[i].price">
    </div>

    <button type="submit" class="btn btn-default">Submit</button>
    <!--(click)="bottleUpdatePriceForm.reset();"-->
</form>

EDIT : adding my component code for regex binding

private pricePattern = /^(((0|[1-9]\d{0,2})(\.\d{2})?)|())$/;

Be it text or number I don't really care, I just need the pattern to work on my input... Any insight or something I am missing ?

Here is a working example in a plunkr : https://plnkr.co/edit/znVaS7?p=info

You can switch the input line in the plunkr to see the different cases :

<input type="text" class="form-control" name="bottlePrice" autocomplete="off"

<input type="number" class="form-control" name="bottlePrice" autocomplete="off" step="any"


Unrelated to the main issue : Is there any way to call the form reset from the component rather than directly in the template ? ==> bottleUpdatePriceForm.reset();

I was wondering, this is just for bonus.

Thanks a lot

Upvotes: 2

Views: 5892

Answers (1)

AVJT82
AVJT82

Reputation: 73387

This is not a direct solution for the not working regex, but this works with the same purpose. So remove the pattern and just change your input with max and min instead:

<input type="number" class="form-control" name="bottlePrice" 
     autocomplete="off" step="any" max="999" min="0"
     [(ngModel)]="bottleArrayToUpdate[i].price">

Upvotes: 1

Related Questions