Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

352
Visualizações
Angular: Number field validation using directive

I am trying to validate a input:number field using directive. The purpose of the field is to accept only numbers between 0-9 or a decimal number up to 3 decimal places (numbers will be positive all time without any symbols).

As there are same type of fields of more than 30 so thought of creating a directive that will prevent users from entering unnecessary characters.

Below is my code for the same along with a Stackblitz sample:

Directive:

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[validTestValue]'
})
export class NumberDirective {

  @HostListener('keydown', ['$event'])
  @HostListener('input', ['$event'])
  onKeyDown(e) {
    const key = ['Backspace', 'Delete', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.'];
    let check = key.includes(e.key) && /^\d{1,7}((.)|(.\d{0,3})?)$/.test(e.target.value);
    console.log(check)
    if (!check) {
      e.preventDefault();
    }
  }
}

HTML:

<input type="number" validTestValue class="testInput-field text-center" />
<!--Same input fields are there many times in my code-->

The problem with this code is that I can enter value as I desired i.e. only digits and the decimal point is accepted but few other issues are arising like below:

  1. Excepted result should be max 7 digits whether or not it is a decimal number. Example: 1, 12, 1234567
  2. If decimal number then max 7 digits before decimal and max 3 digits after decimal. Example: 1, 1.2, 1.12, 1.123
  3. Cannot Backspace (if length reached) or move cursor.
  4. If the field is blank without any default value
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I think the issue is in your regx

/^\d{1,7}((.)|(.\d{0,3})?)

this allows 1 to 7 digits ( {1,7} matches the previous token between 1 and 7 times, as many times as possible )

This is what I'm using currently. It can control how many decimal points allowed in a field

numbers only directive

In template file

<input type="text" numbers-only="2"  placeholder=""
about 4 years ago · Juan Pablo Isaza Relatório

0

As per Dilshan's solution it will only check number of digits after decimal and also it's not validating spaces as per his regex. I am updating Dilshan's solution a bit to meet your requirement as per my understanding.

REGEX: ^([\d]{0,7})((\.{1})([\d]{1,3})?)?$

HTML: <input type="text" validateNumber="7.3" />

This is the Stackblitz solution for your reference.

Hope this helps you 😊.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda