简体   繁体   中英

How can I restrict input to a text-box so that it accepts only numbers and the decimal point( atleast 4 decimals e.g 192.168.192.192)?

I need to restrict input field so that it doesn't accept characters and special symbols. Only accept numbers and 2 or more decimal or period(.).

Note *Even cannot type characters in input field.

html:-

<mat-form-field>
                <input matInput onkeypress="return isNumberKey(this, event);" placeholder="JNDI Name" formControlName="jndiName" [(ngModel)]="body.jndiName" autocomplete="off">
              </mat-form-field>

ts:-

isNumberKey(txt, evt) {

    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode == 46) {
        //Check if the text already contains the . character
        if (txt.value.indexOf('.') === -1) {
            return true;
        } else {
            return false;
        }
    } else {
        if (charCode > 31
             && (charCode < 48 || charCode > 57))
            return false;
    }
    return true;
}

I want a input field in which I can type numeric and period(.) at least 4 dots in that field but I don't want to my form field to accept characters or special symbols. It will accept only and only numbers and dot(s).

What you are looking for is the HTML input pattern .

The pattern attribute specifies a regular expression that the element's value is checked against on form submission.


For IP validation you can use this regular expression : ^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)

Edit :
In order to ignore any other keys than the one you want you can use something like this .

@Directive( {
    selector : '[allow-keys]',
    host : {
        '(keydown)' : 'onKeyUp($event)'
    }
} )
export class AllowKeysDirective {
    @Input( 'allow-keys' ) allowKeys;
    onKeyUp ( $event ) {
        if ( this.allowKeys && !this.allowKeys.includes( $event. keyCode ) ) {
            $event.preventDefault();
        }
    }
}


It is a more "angular-like" way to handle ignoring keystrokes than the one I described in my comment. I created an example to demonstrate its use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM