CaioQuirinoMedeiros / react-native-mask-input

🎭:iphone: A simple and effective Text Input with mask for ReactNative on iOS and Android. Includes obfuscation characters feature.
https://www.npmjs.com/package/react-native-mask-input
MIT License
309 stars 31 forks source link

Date mask accepting month greater than 12 and day greater than 31 #16

Closed joaolobao380 closed 2 years ago

joaolobao380 commented 2 years ago

Mask: Masks.DATE_DDMMYYY

Captura de Tela 2022-01-27 às 17 42 35 Y

CaioQuirinoMedeiros commented 2 years ago

@joaolobao380 this is a generic mask component, its not intended to do such validation... you can create your own mask to do it if you like, would be something like below:

import { Mask } from 'react-native-mask-input';

const DATE_MASK: Mask = (text = '') => {
  const cleanText = text.replace(/\D+/g, '');

  let secondDigitDayMask = /\d/;
  if (cleanText.charAt(0) === '3') {
    secondDigitDayMask = /[01]/
  }

  let secondDigitMonthMask = /\d/
  if (cleanText.charAt(2) === '1') {
    secondDigitMonthMask = /[012]/
  }

  return [/[0-3]/, secondDigitDayMask, '/', /[0-1]/, secondDigitMonthMask, '/', /\d/, /\d/, /\d/, /\d/]
};

I consider this risky, I would rather just warn the user that he entered an invalid date and do any needed validation outside this component

joaolobao380 commented 2 years ago

Understand, thanks dude!! :D

CaioQuirinoMedeiros commented 2 years ago

Updated my comment, there was a mistake on the code, its not [0,1] but [01] for secondDigitDayMask

joaolobao380 commented 2 years ago

I modified it when I went to implement it, but thanks a lot <3

joaolobao380 commented 2 years ago

We can also add:

const DATE_MASK: Mask = (text = '') => {
  const cleanText = text.replace(/\D+/g, '');

  let secondDigitDayMask = /\d/;

  // Avoid typing 00 for the day
  if (cleanText.charAt(0) === '0') {
      secondDigitDayMask = /[1-9]/;
   }
  if (cleanText.charAt(0) === '3') {
    secondDigitDayMask = /[01]/
  }

  let secondDigitMonthMask = /\d/

   // Avoid typing 00 for the month
  if (cleanText.charAt(2) === '0') {
    secondDigitMonthMask = /[1-9]/;
  }
  if (cleanText.charAt(2) === '1') {
    secondDigitMonthMask = /[012]/
  }

  return [/[0-3]/, secondDigitDayMask, '/', /[0-1]/, secondDigitMonthMask, '/', /\d/, /\d/, /\d/, /\d/]
};