Open In App

Restrict EditText Input to Some Special Characters in Android

Last Updated : 09 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In some of the other applications, most of us must have witnessed that while typing in some field, we get a warning or a flash message that certain characters are not allowed or are not accepted as valid input. For example, sometimes, while renaming a file or a folder in Windows, if we simply type in ‘?’, we get a message that ‘?’ is not accepted as valid input. This happens because the character ‘?’ must be having some functional meaning in the file systems of that OS. Similarly, there can be restrictions on other special characters as they might be having some functional significance in the file systems of the OS. Similarly, this concept can be applied to any kind of user inputs. Let us say if the input is the desired username while sign-up, we can apply a similar concept to avoid the use of numbers or special characters. So, in this article, we will show you how you could limit the input to a specific set of characters for EditText in Android.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. We created an EditText, where input can be taken. Note that android:digits attribute allows the given characters only in the input stream.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <EditText
        android:layout_width="match_parent"
        android:layout_height="50sp"
        android:hint="Type something..."
        android:inputType="text"
        android:digits="abcd@#$123"/>
  
</RelativeLayout>


Step 3: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. No additional code is needed inside this file. 

Kotlin




import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
  
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}


Output:

You can see that only those characters are printed in the EditText that has been declared against the android:digits attribute of the EditText.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads