根据身份证号自动填入性别、年龄、出生日期

170 阅读1分钟

sfz.gif


function getIdentityInfo(idCard) {
    // 检查身份证号长度是否合法
    if (!idCard || idCard.length !== 18) {
        return {
            age: null,
            gender: null,
            birthDate: null
        };
    }

    // 提取出生日期
    const birthYear = parseInt(idCard.substring(6, 10), 10);
    const birthMonth = parseInt(idCard.substring(10, 12), 10);
    const birthDay = parseInt(idCard.substring(12, 14), 10);
    const birthDate = new Date(birthYear, birthMonth - 1, birthDay); // 月份从0开始

    // 验证出生日期是否有效
    if (
        birthDate.getFullYear() !== birthYear ||
        birthDate.getMonth() !== birthMonth - 1 ||
        birthDate.getDate() !== birthDay
    ) {
        return {
            age: null,
            gender: null,
            birthDate: null
        };
    }

    // 计算年龄
    const today = new Date();
    let age = today.getFullYear() - birthYear;
    if (today.getMonth() < birthMonth - 1 || (today.getMonth() === birthMonth - 1 && today.getDate() < birthDay)) {
        age--;
    }

    // 提取性别(第17位,奇数为男性,偶数为女性)
    const genderCode = parseInt(idCard.substring(16, 17), 10);
    const gender = genderCode % 2 === 1 ? '男' : '女';

    // 格式化出生日期为 YYYY-MM-DD
    const formattedBirthDate = `${birthYear}-${birthMonth.toString().padStart(2, '0')}-${birthDay.toString().padStart(2, '0')}`;

    return {
        age: age,
        gender: gender,
        birthDate: formattedBirthDate
    };
}

// 示例用法
const idCard =this.formModel.d10; // 示例身份证号
const identityInfo = getIdentityInfo(idCard);
this.formModel.d13 = identityInfo.age;
this.formModel.d9 = identityInfo.gender;
this.formModel.d12 = identityInfo.birthDate;