Files
aurora-admin/frameworks/IDCardInput.jsx
T

60 lines
2.1 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React, { useState, useMemo } from 'react';
import './IDCardInput.css';
const WEIGHTS = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
const CHECK = '10X98765432';
function validate(v) {
if (!/^\d{17}[\dX]$/.test(v)) return null;
let sum = 0;
for (let i = 0; i < 17; i++) sum += parseInt(v[i], 10) * WEIGHTS[i];
if (CHECK[sum % 11] !== v[17]) return null;
const birth = v.slice(6, 14);
return { birth: birth.slice(0, 4) + '-' + birth.slice(4, 6) + '-' + birth.slice(6, 8), gender: parseInt(v[16], 10) % 2 === 1 ? '男' : '女' };
}
export default function IDCardInput({ modelValue = '', placeholder = '请输入 18 位身份证号', onChange }) {
const [focused, setFocused] = useState(false);
const result = useMemo(() => validate(modelValue.toUpperCase()) || {}, [modelValue]);
const valid = !!result.birth;
const invalid = modelValue.length === 18 && !result.birth;
const tipClass = !modelValue ? '' : valid ? 'valid' : invalid ? 'invalid' : '';
const tipText = !modelValue
? '示例:11010119900307657X'
: modelValue.length < 18
? '已输入 ' + modelValue.length + ' 位,继续…'
: valid
? '校验通过'
: '身份证号校验失败,请检查';
const onInput = (e) => {
const v = e.target.value.replace(/[^0-9Xx]/g, '').toUpperCase().slice(0, 18);
e.target.value = v;
if (onChange) onChange(v);
};
return (
<div className="aa-idcard">
<div
className={'aa-idcard-field' + (focused ? ' is-focus' : '') + (valid ? ' is-valid' : '') + (invalid ? ' is-invalid' : '')}
>
<input
className="aa-idcard-input"
value={modelValue}
maxLength={18}
placeholder={placeholder}
onInput={onInput}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
/>
</div>
{result.birth && (
<div className="aa-idcard-info">
<span>出生日期:<b>{result.birth}</b></span>
<span>性别:<b>{result.gender}</b></span>
</div>
)}
<div className={'aa-idcard-tip ' + tipClass}>{tipText}</div>
</div>
);
}