'Validating EditText to having time in kotlin Android

I have a screen which have 2 edit text one edit text shows hour and other shows minute

enter image description here

I have number of validations that needs to be performed on this

hour edit Text

  • check if entered string if of 12 hour format
  • if user enter like 70 show error Tost and convert it ->07
  • if enter some number like 73 show error and remove last char and make it like ->07

minute Edit Text

  • value should be from 0>59

  • if entered 60 make it 00

  • if value entered is 80 ->show error ->convert it to 08

  • if value entered is 89 -> show error -> remove char and show as 08

     beginHour!!.addTextChangedListener(object : TextWatcher {
         override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
         override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
             if (p0.toString().isNotEmpty()) {
                 if (TextUtils.isDigitsOnly(p0.toString())) {
                     val hour = Integer.parseInt(p0.toString());
                     if (hour > maxHourValue || hour <= 0) {
                         shortToast(errorMessage)
                         beginHour!!.setText(beginHourString)
                     } else {
                         beginHourString = hour.toString()
                     }
                 } else {
                     shortToast(errorMessage)
                     beginHour!!.setText(beginHourString)
                 }
             } else {
                 beginHourString = ""
             }
         }
    
         override fun afterTextChanged(p0: Editable?) {
         }
     })
    
     beginHour!!.setOnFocusChangeListener { _, hasFocus ->
         if (!hasFocus) {
             try {
                 if (beginHour!!.text.isNullOrEmpty()) {
                     beginHour!!.setText("08")
                     beginHourString = "08"
                 }
                 val hour = 
             Integer.parseInt(beginHour!!.text.toString())
    
                if (value in 0..9) {
                   beginHour.setText("0$value")
             } else {
             beginHour.setText(value.toString())
              }
    
    
             } catch (exception: NumberFormatException) {
             }
         }
     }
    

can anyone suggest and guide me how to implement these validations



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source