Skip to content

Commit

Permalink
feat: 增加验证身份证号码的范围合理性(1850-今天)
Browse files Browse the repository at this point in the history
  • Loading branch information
jinye authored and CheshireJCat committed Mar 11, 2024
1 parent 3b1d7d2 commit 286c971
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
6 changes: 5 additions & 1 deletion packages/amis-core/src/utils/validateId.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import moment from 'moment';

/**
* 身份证号码校验,(没有校验城市和区县)
*
Expand Down Expand Up @@ -142,7 +144,9 @@ function verifyRegion(province: string, city: string, country: string) {
}

function verifyBirthday(birthday: any) {
return !isNaN(+birthday);
const min = moment(new Date('1850-01-01')); // 还有1850年前的人活着吗?
const max = moment().endOf('day'); // 最大值是今天
return !isNaN(+birthday) && moment(birthday).isBetween(min, max);
}

/**
Expand Down
53 changes: 53 additions & 0 deletions packages/amis/__tests__/utils/validations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1416,4 +1416,57 @@ describe('validation: isId', () => {
}
]);
});

test('validation: isId invalid when the birthday is before 1850', () => {
expect(
validate(
'14112918490909001X',
{},
{
isId: true
}
)
).toMatchObject([
{
msg: 'validate.isId',
rule: 'isId'
}
]);
});

test('validation: isId invalid when the birthday is after today', () => {
const tomorrow = new Date(new Date().getTime() + 1000 * 60 * 60 * 24);
const year = tomorrow.getFullYear();
const month = tomorrow.getMonth() + 1;
const day = tomorrow.getDate();
let id = `141129${year}${month < 10 ? '0' + month : month}${
day < 10 ? day : '0' + day
}001`;
id = `${id}${generateCheckCode(id)}`;
expect(
validate(
id,
{},
{
isId: true
}
)
).toMatchObject([
{
msg: 'validate.isId',
rule: 'isId'
}
]);
});
});

// 生成身份证验证码
function generateCheckCode(id: string) {
const arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
const arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
let cardTemp = 0;
for (let i = 0; i < 17; i++) {
cardTemp += +id.slice(i, i + 1) * arrInt[i];
}
return arrCh[cardTemp % 11];
}

0 comments on commit 286c971

Please sign in to comment.