2

I created a directive that validates what the user enters in text field. User can enter numbers, dots and commas but not anything else.

The validator works when entering numbers, but I cannot enter commas and dots.

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

@Directive({
  selector: '[appInputValidator]'
})
export class InputValidatorDirective {

private regex: RegExp = new RegExp(/^[0-9]{1,2}([,.][0-9]{1,2})?$/);

// Allow key codes for special events
// Backspace, tab, end, home
private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];

constructor(private el: ElementRef) {
}

@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
    debugger
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
        return;
    }

    let current: string = this.el.nativeElement.value;
    let next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex)) {
        event.preventDefault();
    }
}

}

I've tested the regex online and it works for numbers, dots and commas but inside the app I can't enter dots or commas. What is wrong?

7
  • Because when you enter 12., it doesn't match the regex Commented Aug 28, 2018 at 8:00
  • Am I using wrong function (match) ? Is it possible restrict input so that comma and dot cannot be first characters? Commented Aug 28, 2018 at 8:03
  • No. Since you are checking every time user press a key, when user wants to enter '12.3', on the 3rd key stroke, the string would become 12., which fails the regex check. Solution is either allow user to enter anything, and validate once focus leaves the input, or depending on the input, you might be able to craft a regex that allows the intermediate states Commented Aug 28, 2018 at 8:05
  • Can the regex be modified so that commas and dots cannot be first characters in the string? Commented Aug 28, 2018 at 8:06
  • 1
    Try private regex: RegExp = /^[0-9]{1,2}([,.][0-9]{0,2})?$/; Commented Aug 28, 2018 at 8:54

1 Answer 1

2

You may use

private regex: RegExp = /^[0-9]{1,2}([,.][0-9]{0,2})?$/;
                                               ^

Note that {0,2} quantifier makes [0-9] match zero, one or two digits, and thus the 2. like values will no longer stop user from typing a number with a fractional part.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.