captcha.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // components/captcha/captcha.js
  2. Component({
  3. /**
  4. * 组件的属性列表
  5. */
  6. properties: {
  7. phone: {
  8. type: String,
  9. required: true
  10. },
  11. },
  12. /**
  13. * 组件的初始数据
  14. */
  15. data: {
  16. generateCode: '-999999', // 点击发送验证码时生成的验证码
  17. userCode: '', // 用户输入的验证码
  18. defaultCode: '989898', // 测试时使用
  19. },
  20. /**
  21. * 组件的方法列表
  22. */
  23. methods: {
  24. /**
  25. * 监听验证码输入
  26. * @param {*} e
  27. */
  28. onInputCode(e) {
  29. this.setData({
  30. userCode: e.detail.value
  31. })
  32. },
  33. // 获取验证码
  34. getCode() {
  35. const { phone } = this.data;
  36. if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
  37. wx.showToast({
  38. title: '请输入有效的手机号码',
  39. icon: 'none'
  40. });
  41. return;
  42. }
  43. const generateCode = this.generateCode(); // 本地生成验证码(用于发送)
  44. // 保存验证码到 data
  45. this.setData({ generateCode });
  46. wx.cloud.callFunction({
  47. // 云函数名称
  48. name: 'lxp',
  49. // 传给云函数的参数
  50. data: {
  51. mobile: this.data.phone,
  52. code: generateCode,
  53. },
  54. }).then(res => {
  55. if (res.result.response.code === 200) {
  56. console.log('数据获取成功 =>', res.result.response);
  57. wx.showToast({
  58. title: '验证码发送成功',
  59. icon: 'none'
  60. });
  61. } else {
  62. console.error('数据获取失败 =>', res.result.response);
  63. wx.showToast({
  64. title: '验证码发送失败',
  65. icon: 'none'
  66. });
  67. }
  68. }).catch(error => {
  69. console.error(error)
  70. wx.showToast({
  71. title: '验证码发送失败',
  72. icon: 'none'
  73. });
  74. })
  75. },
  76. /**
  77. * 生成验证码
  78. */
  79. generateCode() {
  80. return Math.floor(100000 + Math.random() * 900000).toString();
  81. },
  82. /**
  83. * 校验验证码
  84. */
  85. validCaptcha() {
  86. const { generateCode, userCode, defaultCode } = this.data
  87. const flag = generateCode === userCode || defaultCode === userCode
  88. const result = {
  89. flag,
  90. msg: '',
  91. }
  92. if (!flag) {
  93. result.msg = '验证码输入错误'
  94. }
  95. if (!userCode) {
  96. result.msg = '请输入验证码'
  97. }
  98. return result
  99. },
  100. }
  101. })