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

Angular 4表单实现国籍/身份证/年龄校验需求咨询

Angular 4 表单自定义校验实现方案

嘿,针对你提出的表单校验需求,我整理了一套贴合Angular 4模板驱动表单的实现方案,分两部分搞定你的问题:

一、身份证号的国籍关联校验

先明确你的规则:

  • 国籍为MY时:身份证支持7位旧版或12位新版;如果是12位新版,需校验前6位(我默认前6位为纯数字,你可以根据实际业务规则调整,比如改为校验合法日期格式)
  • 非MY国籍时:身份证必须是9位纯数字

1. 编写自定义校验函数

在组件类中添加校验逻辑,它会根据当前选中的国籍判断身份证号是否合法:

import { FormControl, ValidatorFn } from '@angular/forms';

// 身份证号自定义校验器,接收国籍作为参数
identityNumberValidator(nationality: string): ValidatorFn {
  return (control: FormControl) => {
    const idNumber = control.value;
    if (!idNumber) return null; // 必填项校验已由`required`处理

    // 非马来西亚国籍规则:必须是9位纯数字
    if (nationality !== 'MY') {
      if (idNumber.length !== 9 || !/^\d{9}$/.test(idNumber)) {
        return { invalidNonMYId: true };
      }
    } else {
      // 马来西亚国籍规则:7位或12位纯数字
      if (!/^\d{7}$/.test(idNumber) && !/^\d{12}$/.test(idNumber)) {
        return { invalidMYId: true };
      }
      // 12位新版身份证:校验前6位(示例为纯数字,可替换为日期校验等规则)
      if (idNumber.length === 12 && !/^\d{6}/.test(idNumber)) {
        return { invalidNewMYId: true };
      }
    }
    return null; // 校验通过
  };
}

2. 绑定校验器到模板并添加错误提示

修改表单模板,给身份证输入框绑定校验器,同时补充对应的错误提示:

<div class="form-group">
  <label for="Nationality">Nationality</label>
  <select id="Nationality" name="Nationality" [(ngModel)]="Nationality" class="form-control">
    <option value="MY">Malaysian</option>
    <option value="SG">Singaporean</option>
    <option value="IN">Indonesian</option>
  </select><br>
</div>

<div class="form-group">
  <label>Identity No: </label>
  <input 
    type="text" 
    name="Identity_No" 
    id="Identity_No" 
    placeholder="Identity No" 
    [(ngModel)]="identityNo"
    #IdentityNo="ngModel" 
    required 
    pattern="[0-9]+"
    [ngModelOptions]="{updateOn: 'blur'}" <!-- 失去焦点时校验,提升用户体验 -->
    [validator]="identityNumberValidator(Nationality)"
  ><br>
</div>

<div *ngIf="IdentityNo.touched" class="alert alert-danger">
  <div *ngIf="IdentityNo.errors?.required">Identity No is required</div>
  <div *ngIf="IdentityNo.errors?.pattern">Identity No can only contain numbers</div>
  <div *ngIf="IdentityNo.errors?.invalidNonMYId">Non-Malaysian Identity No must be exactly 9 digits</div>
  <div *ngIf="IdentityNo.errors?.invalidMYId">Malaysian Identity No must be 7 or 12 digits</div>
  <div *ngIf="IdentityNo.errors?.invalidNewMYId">First 6 digits of new Malaysian Identity No are invalid</div>
</div>

记得在组件类中声明对应变量:

Nationality: string = '';
identityNo: string = '';

二、年龄校验(小于19岁禁止注册)

这个需求我们在注册按钮点击时触发校验(更符合常规注册流程),也可以扩展为实时校验:

1. 组件类添加年龄计算和注册逻辑

birthdate: string = '';

// 根据生日计算年龄
calculateAge(birthdateStr: string): number {
  const birthDate = new Date(birthdateStr);
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  // 处理未到生日的情况,年龄减1
  const monthDiff = today.getMonth() - birthDate.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
}

// 注册按钮点击事件
onRegister() {
  const userAge = this.calculateAge(this.birthdate);
  if (userAge < 19) {
    alert('Sorry, you must be at least 19 years old to register.');
    return;
  }
  // 校验通过,执行你的注册逻辑
  console.log('Registration successful!');
}

2. 模板绑定生日值和注册按钮

修改生日输入框绑定,并添加注册按钮(表单不合法时按钮禁用):

<div class="form-group">
  <label>Birthdate: </label>
  <input 
    type="date" 
    name="Birthdate" 
    id="Birthdate" 
    placeholder="Birthdate" 
    [(ngModel)]="birthdate"
    #Bdate="ngModel" 
    required
  ><br>
</div>

<div *ngIf="Bdate.touched" class="alert alert-danger">
  <div *ngIf="Bdate.errors?.required">Birth Date is required</div>
</div>

<button 
  class="btn btn-primary" 
  (click)="onRegister()" 
  [disabled]="!IdentityNo.valid || !Bdate.valid"
>
  Register
</button>

额外小提示

如果你想让年龄校验实时显示错误提示(比如用户选完生日立刻提示),可以把年龄校验封装成自定义校验器绑定到生日输入框,逻辑类似身份证校验器。另外,新版MY身份证的前6位如果是出生日期,可将正则改为/^(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])/来校验日期合法性。

内容的提问来源于stack exchange,提问作者Calvin Tkh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:14:04