Good day. I have an android app where I allow the user to input their birthday into the edit texts.
Edit text has the following attributes:
<com.google.android.material.textfield.TextInputLayout
style="@style/CustomOutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:boxBackgroundColor="@color/white"
android:hint="Birthday MM/DD/YYYY">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/et_new_member_birthday"
android:textColor="@color/black"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="16sp"
android:inputType="date"/>
</com.google.android.material.textfield.TextInputLayout>
How can I check if their input follows the mm/DD/yyyy format?
Editted: I tried adding the following block, unfortunately, it crashed my app.
private fun isDateValid(date: String): Boolean {
val format = "MM/dd/yyyy"
return try {
val formatter = DateTimeFormatter.ofPattern(format)
val convertedDate = LocalDate.parse(date, formatter)
Toast.makeText(this, "Date is $convertedDate", Toast.LENGTH_SHORT).show()
true
} catch (e: ParseException) {
Toast.makeText(this, "Error parsing date.", Toast.LENGTH_LONG).show()
false
}
}
And I'm calling this method via Activity:
val etBirthday = binding.etNewMemberBirthday.text.toString()
...
TextUtils.isEmpty(etBirthday) || isDateValid(etBirthday)->{
showErrorSnackBar(binding.root, "Please input a valid date.", true)
false
}
...