Android Kotlin - EditText Password Validation (Breakdown)
This code demonstrates password validation for an EditText field in an Android application written in Kotlin. Here's a breakdown of the functionalities:
Layout and References:
- The
activity_main.xml
file defines the user interface with anEditText
for password input and aTextView
to display password requirements. - In
MainActivity.kt
, theonCreate
function retrieves references to these UI elements usingfindViewById
.
- The
Password Rules:
- The
textView
displays the password requirements: minimum length of 8 characters, containing at least one uppercase letter, one number, and one special character.
- The
Password Validation with TextWatcher:
- A
TextWatcher
is added to theeditText
. This listener gets triggered whenever the text in the edit text changes. - Inside the
onTextChanged
method, the code checks if the entered text is a valid password using theisValidPassword
extension function and if its length is at least 8 characters.- If valid, the error message on the
editText
is cleared. - If invalid, an error message "invalid password" is set on the
editText
.
- If valid, the error message on the
- A
Password Validation Function:
- The
isValidPassword
extension function takes aCharSequence
(which can be a String) as input. - It uses a regular expression (
passwordPattern
) to define the password format. This pattern ensures the password has:- At least one digit (
[0-9]
) - At least one uppercase letter (
[A-Z]
) - At least one special character (
[@#$%^&+=!])
) - No whitespace characters (
\\S+$
) - Minimum length of 4 characters (
.{4,}$
)
- At least one digit (
- The function compiles the pattern and uses a matcher to check if the input matches the defined format. It returns
true
if the password is valid andfalse
otherwise.
- The
Summary
This code effectively implements password validation for an EditText field in an Android app. It leverages a TextWatcher to monitor user input and validates the password against a defined pattern using regular expressions. This approach ensures secure password creation by enforcing complexity requirements.
MainActivity.kt
package com.cfsuman.kotlintutorials
import android.app.Activity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import android.widget.TextView
import java.util.regex.Pattern
class MainActivity : Activity() {
private lateinit var editText:EditText
private lateinit var textView:TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get the widgets reference from XML layout
editText = findViewById(R.id.editText)
textView = findViewById(R.id.textView)
// show password rules in text view
textView.text = "Password minimum length 8"
textView.append("\n1 uppercase")
textView.append("\n1 number")
textView.append("\n1 special character")
// add text changed listener for edit text
editText.addTextChangedListener(object: TextWatcher {
override fun beforeTextChanged(
s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(
s: CharSequence?, start: Int, before: Int, count: Int) {
s?.apply {
// check user input a valid formatted password
if (isValidPassword() && toString().length>=8) {
editText.error == null
}else{
// show error on input invalid password
editText.error = "invalid password."
}
}
}
override fun afterTextChanged(s: Editable?) {
}
})
}
}
// extension function to validate password rules/patterns
fun CharSequence.isValidPassword(): Boolean {
val passwordPattern =
"^(?=.*[0-9])(?=.*[A-Z])(?=.*[@#$%^&+=!])(?=\\S+$).{4,}$"
val pattern = Pattern.compile(passwordPattern)
val matcher = pattern.matcher(this)
return matcher.matches()
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="32dp">
<EditText
android:id="@+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginEnd="12dp"
android:padding="12dp"
android:textSize="30sp"
android:inputType="textPassword"
android:fontFamily="sans-serif-condensed-medium"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.12" />
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:fontFamily="sans-serif-condensed-medium"
android:gravity="center"
android:padding="8dp"
android:textColor="#4F42B5"
android:textSize="22sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText"
tools:text="TextView" />
</androidx.constraintlayout.widget.ConstraintLayout>
- android kotlin - Volley JsonArrayRequest
- android kotlin - Volley JsonObjectRequest
- android kotlin - Volley image request
- android kotlin - Chip border color
- android kotlin - Chip background color
- android kotlin - Chip checked color programmatically
- android kotlin - ChipGroup single selection
- android kotlin - NumberPicker string values
- android kotlin - NumberPicker divider height
- android kotlin - NumberPicker text size
- android kotlin - NumberPicker text color
- android kotlin - Disable soft keyboard on NumberPicker
- android kotlin - EditText phone number validation
- android kotlin - EditText live characters count
- android kotlin - EditText first letter capitalization