regexangularangular7angular-validationangular-validator

Angular7 Validation Pattern to accept only integers and double values


I have wasted a lot of time on this already :(.

I want to accept only the integer or the double-positive numbers: ex: 40000, 500.0000, 400.1234 I managed to do that for the integers:

// somewhere at the code 
export const NUMERIC_PATTREN = '^-?[0-9]\\d*(\\.\\d{1,2})?$';

// component code:
  amount: [{ value: entry.amount, disabled: false }, [Validators.required,Validators.pattern(NUMERIC_PATTREN )]],


However, the input is not accepting values from the format 500.0000 or 400.1234. can anybody help me figure this out please.

Update I want to limit the number of places after the point too.


Solution

  • This Worked for me:

    export const NUMERIC_PATTREN = '^-?[0-9]\\d*(\\.\\d{1,4})?$';
    
    

    this will accept an integer number or a double number with maximum 4 places after the point.

    If you want to increase or decrease the places after the point, you need to play with 4, ex:

    export const NUMERIC_PATTREN = '^-?[0-9]\\d*(\\.\\d{1,3})?$'; //accepts only 3 places after the point
    
    

    If you want unlimited places after the point you need to use:

    export const NUMERIC_PATTREN = '^-?[0-9]\\d*(\\.\\d*)?$'; //accepts endless places 
    
    

    If you don't want the user to enter a zero to the left, then you need to start the domain from 1:

    ^-?[1-9]\\d*(\\.\\d{1,4})?$