Home > Back-end >  How to make pattern in TextInput used for credit card in react native?
How to make pattern in TextInput used for credit card in react native?

Time:07-29

I want to make pattern text input for months and years. So, I made some logic but it's not working.

Below is the code:

const [monthYear, setMonthYear] = useState(null)

function _handlingMonthYear(number) {
  setMonthYear(number.replace(/\s?/g, '').replace(/(\d{2})/g, '$1 ').trim());
}

<TextInput
  onChangeText={(text) => _handlingMonthYear(text)}
  placeholder='MM/YY'
  value={monthYear}
/>

I want to make that if the user type 1234 then it should appear as 12/34 in TextInput.

CodePudding user response:

you can use this regular expression

const monthYear=/(0[1-9]|1[0-2])\/(\d{4}[^0-9])/
var testDate="01/2022"
console.log("(monthYear.test(testDate))","it will log true")
var testDate="13/2022"
console.log("(monthYear.test(testDate))","it will log false")

CodePudding user response:

I found this solution for the format look like as 'MM/YY'.

Below is the full code of my solution. It's working.

function _handlingMonthYear(number) {
  setMonthYear(number
    .replace(
      /^([1-9]\/|[2-9])$/g, '0$1/'
    ).replace(
      /^(0[1-9]|1[0-2])$/g, '$1/' 
    ).replace(
      /^([0-1])([3-9])$/g, '0$1/$2'
    ).replace(
      /^(0?[1-9]|1[0-2])([0-9]{2})$/g, '$1/$2' 
    ).replace(
      /^([0] )\/|[0] $/g, '0' 
    ).replace(
      /[^\d\/]|^[\/]*$/g, '' 
    ).replace(
      /\/\//g, '/'
    )
  );
}
  • Related