skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

    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, '/'
        )
      );
    }
    

  2. 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")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search