CaioQuirinoMedeiros/react-native-mask-input

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

Closed this issue · 5 comments

Mask: Masks.DATE_DDMMYYY

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

@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

Understand, thanks dude!! :D

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

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

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/]
};