转base64、随机生成一个18位的Id、数字和字母输入验证、身份证校验等

1、定义文件转换为 Base64 的函数

// 定义文件转换为 Base64 的函数
  convertFileToBase64(file, callback) {
    const reader = new FileReader(); // 创建 FileReader 实例
    reader.onload = function (e) {
      const base64String = e.target.result; // 获取 Base64 编码
      callback(base64String); // 调用回调函数,传递 Base64 编码
    };
    reader.readAsDataURL(file); // 读取文件内容为 Base64 编码
  },

FileReader 是一个 Web API,用于在浏览器中读取本地文件的内容。它允许用户通过 或拖放操作选择文件,并在前端代码中异步读取文件内容,而无需将文件上传到服务器。FileReader 提供了多种方法来读取文件,包括读取为文本、二进制字符串或数据 URL。

2、随机生成一个18位的Id

  generateRandomId(length = 18) {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
      result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return result;
  },

3、数字和字母输入验证

// 
  validateInputNZ(input) {
    // 使用正则表达式校验是否只包含数字和字母
    const regex = /^[a-zA-Z0-9]+$/;
    return regex.test(input);
  },

4、身份证校验

 // 身份证校验
  isValidIDCard(idCard) {
    if (!idCard || idCard.length !== 18) {
      return false; // 身份证号必须是18位
    }

    const reg = /^[1-9]\d{5}(18|19|20)?\d{2}((0[1-9])|(10|11|12))(([0|1|2][0-9])|10|20|30|31)\d{3}(\d|[Xx])$/;
    if (!reg.test(idCard)) {
      return false; // 格式校验失败
    }

    // 校验出生日期
    const birthDate = idCard.substring(6, 14);
    const year = parseInt(birthDate.substring(0, 4), 10);
    const month = parseInt(birthDate.substring(4, 6), 10);
    const day = parseInt(birthDate.substring(6, 8), 10);

    const date = new Date(year, month - 1, day);
    if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
      return false; // 出生日期无效
    }

    // 校验码校验
    const factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const checksum = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
    let sum = 0;

    for (let i = 0; i < 17; i++) {
      sum += parseInt(idCard[i], 10) * factors[i];
    }

    const mod = sum % 11;
    const checkDigit = checksum[mod];

    return checkDigit === idCard[17].toUpperCase(); // 校验码是否匹配
  },

5、电话号或手机号校验

// 
  isValidPhoneNumber(number) {
    const mobileRegex = /^1[3-9]\d{9}$/; // 手机号校验
    const phoneRegex = /^(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$/; // 电话号码校验

    return mobileRegex.test(number) || phoneRegex.test(number);
  },

6、字母和数字组成的18位校验

 isValid18CharId(id) {
    const regex = /^[A-Za-z0-9]{18}$/;
    return regex.test(id);
  },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长影缚苍龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值