You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何限制Angular输入框仅输入数字与英文句点且至少含4个句点?

Solution for Input Validation (Numbers + Multiple Periods)

Hey there! Let's fix your input validation to meet your requirements. First, we'll adjust the keypress handler to allow multiple periods along with numbers, then add validation to ensure there are at least 4 periods in the input.

Step 1: Modify the Keypress Handler (isNumberKey)

The original function only allows one period—let's update it to permit multiple periods, while still blocking letters and special characters entirely.

Here's the updated TS code:

isNumberKey(txt: HTMLInputElement, evt: KeyboardEvent): boolean {
  const charCode = evt.which || evt.keyCode;
  
  // Allow control keys (backspace, delete, tab, etc.) so users can edit normally
  if (charCode <= 31) {
    return true;
  }

  // Only allow numbers (0-9) and the English period (.)
  if ((charCode >= 48 && charCode <= 57) || charCode === 46) {
    return true;
  }

  // Block all other characters (letters, special symbols)
  return false;
}

What changed:

  • Removed the restriction that limited input to one period
  • Explicitly whitelisted only numbers and the period character
  • Kept essential control keys functional for a smooth editing experience

Step 2: Add Validation for Minimum 4 Periods

Next, we need to ensure the final input contains at least 4 periods. Since you're using Angular's FormControl, adding a custom validator is the most robust way to enforce this (it also catches invalid pasted content, which keypress handlers can't always do).

Update your Form Control Setup

In your component's TS file, add a custom validator and attach it to your form control:

import { FormBuilder, Validators, AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';

// ...

// Custom validator to check for a minimum number of periods
function minimumPeriods(requiredCount: number): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const inputValue = control.value;
    if (!inputValue) return null; // Skip validation for empty input
    
    const periodCount = (inputValue.match(/\./g) || []).length;
    return periodCount >= requiredCount ? null : { insufficientPeriods: true };
  };
}

// Initialize your form with the new validator
this.yourForm = this.fb.group({
  jndiName: ['', [
    Validators.required,
    minimumPeriods(4) // Enforce at least 4 periods
  ]]
});

(Replace yourForm with your actual form variable name)

Show Validation Errors in HTML

Update your mat-form-field to display a user-friendly error when the period count is too low:

<mat-form-field> 
  <input 
    matInput 
    onkeypress="return isNumberKey(this, event);" 
    placeholder="JNDI Name" 
    formControlName="jndiName" 
    [(ngModel)]="body.jndiName" 
    autocomplete="off"
  >
  <mat-error *ngIf="yourForm.get('jndiName')?.errors?.insufficientPeriods">
    Input must contain at least 4 periods (e.g., 192.168.192.192.192)
  </mat-error>
  <mat-error *ngIf="yourForm.get('jndiName')?.errors?.required">
    JNDI Name is required
  </mat-error>
</mat-form-field>

Step 3: Optional - Prevent Consecutive Periods

If you want to avoid messy input like 192..168, add an extra check to the keypress handler to block back-to-back periods:

isNumberKey(txt: HTMLInputElement, evt: KeyboardEvent): boolean {
  const charCode = evt.which || evt.keyCode;
  
  if (charCode <= 31) {
    return true;
  }

  // Allow numbers
  if (charCode >= 48 && charCode <= 57) {
    return true;
  }

  // Allow period only if the last character isn't already a period
  if (charCode === 46) {
    return txt.value[txt.value.length - 1] !== '.';
  }

  return false;
}

Key Notes

  • Combining keypress blocking with Angular form validators ensures both real-time input restriction and final validation (critical for handling pasted content).
  • The validator works independently of the keypress handler, so even if a user bypasses the keypress check (e.g., via browser dev tools), the form will still reject invalid input.

内容的提问来源于stack exchange,提问作者Nisha Yadav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:47:41