android EditText alphabet-only validation - android

i wanted to validate a EditText and see if all of the letters are alphabet. it should be able to handle multiple EditText. i need a way to prevent user from entering anything other then alphabet.
userTextInput=(EditText)findViewById(R.id.textInput);
userTextInput.addTextChangedListener(this);
public void afterTextChanged(Editable edit) {
String textFromEditView = edit.toString();
//first method
ArrayList[] ArrayList;
//ArrayList [] = new ArrayList;
for(int i=0; i<=textFromEditView.length(); i++)
{
if(textFromEditView[i].isLetter() == false)
{
edit.replace(0, edit.length(), "only alphabets");
}
}
//second method
try
{
boolean isOnlyAlphabet = textFromEditView.matches("/^[a-z]+$/i");
if(isOnlyAlphabet == false)
{
edit.replace(0, edit.length(), "only alphabets");
}
}
catch(NumberFormatException e){}
}
for my second method the moment i enter anything, number or alphabet, my app crash.
i have test my first method because it has the error textFromEditView must be an array type bue is resolved as string. can you help me to improve my code.

I think you'd do better using InputFilter:
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence src, int start, int end,
Spanned d, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (!Character.isLetter(src.charAt(i))) {
return src.subSequence(start, i-1);
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});
Code modified from: How do I use InputFilter to limit characters in an EditText in Android?

android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
How to create EditText accepts Alphabets only in android?

You can set the inputType of the EditText. More Information here and here.

Related

How to validate edit text field to allow user enter only text input in android? [duplicate]

This question already has answers here:
How to create EditText accepts Alphabets only in android?
(12 answers)
Closed 5 years ago.
I need to validate the text field to input only text. No numeric or special characters allowed.
Try this one bro
android:digits=" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
set edittext property with capital and small
You can do it using regex, validate users input. Use the following function:
public boolean AlphaCheck(String name) {
return name.matches("[a-zA-Z]+");
}
Send the string(users input) to this function and if the input is valid it will return true and you can then proceed based on that.
Here is another way to do it
public boolean AlphaCheck(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
You can create a filter for this
private String unwantedChars = "~#^|$%&*!1234567890";
private InputFilter filter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (source != null && unwantedChars.contains(("" + source))) {
return "";
}
return null;
}
};
editText.setFilters(new InputFilter[] { filter });

How to detect emoticons in EditText in android

I want to detect whether my EditText contains smilie (emoticons) or not. But I have no idea that how to detect them.
To disable emoji characters when typing on the keyboard I using the following filter:
InputFilter filter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
int type = Character.getType(source.charAt(i));
//System.out.println("Type : " + type);
if (type == Character.SURROGATE || type == Character.OTHER_SYMBOL) {
return "";
}
}
return null;
}
};
mMessageEditText.setFilters(new InputFilter[]{filter});
If you need only detect if EditText contains any emoji character you can use this priciple (Character.getType()) in android.text.TextWatcher interface implementation (in onTextChange() or afterTextChanged() method) or e.g. use simple for cycle on mMessageEditText.getText() (returns CharSequence class) with charAt() method.
If by simile you are referring to the figure of speech, you can use .getText() and the String method .contains(String) to check whether it contains the Strings "like" or "as".
Snippet:
EditText myEditText = (EditText)findViewById(R.id.myEditText);
String input = myEditText.getText();
if(input.contains("like") || input.contains("as"))
{
//code
}
It depends the way you are implementing simleys in your edittext. if you are using motioons you can do this using a trick. You can set a condtion whenever a simpley a added you can add some type of keyword to arrayList and whenever smiley is remover you can remove that keyword from arrayList. And at last you can check that list whether that simley is added to it or not by processing the arrayList items.
for ex...
if(Smiley_added){
arraylist.add(smiley_code,i);
}
if(simley_removed){
arraylist.remove(smileycode,i);
}
if(arraylist.get(i).equals("smileyCode")){
do this....
}

Validation allow only number and characters in edit text in android

In my application I have to validate the EditText. It should only allow character, digits, underscores, and hyphens.
Here is my code:
edittext.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// validation codes here
location_name=s.toString();
Toast.makeText(getApplicationContext(),location_name, Toast.LENGTH_SHORT).show();
if (location_name.matches(".*[^a-z^0-9].*")) {
location_name = location_name.replaceAll("[^a-z^0-9]", "");
s.append(location_name);
s.clear();
Toast.makeText(getApplicationContext(),"Only lowercase letters and numbers are allowed!",Toast.LENGTH_SHORT).show();
}
}
});
location.add(location_name);
When I enter input into EditText, the application is force closed.
Instead of using your "manual" checking method, there is something very easy in Android:
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start,
int end, Spanned dest, int dstart, int dend) {
for (int i = start;i < end;i++) {
if (!Character.isLetterOrDigit(source.charAt(i)) &&
!Character.toString(source.charAt(i)).equals("_") &&
!Character.toString(source.charAt(i)).equals("-"))
{
return "";
}
}
return null;
}
};
edittext.setFilters(new InputFilter[] { filter });
Or another approach: set the allowed characters in the XML where you are creating your EditText:
<EditText
android:inputType="text"
android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm,_,-"
android:hint="Only letters, digits, _ and - allowed" />
<EditText
android:inputType="text"
android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm,_,-"
android:hint="Only letters, digits, _ and - allowed"
/>
the above code will also include , additionally to avoid , use the following code
<EditText
android:inputType="text"
android:digits="0123456789qwertzuiopasdfghjklyxcvbnm_-"
android:hint="Only letters, digits, _ and - allowed"
/>
This can be useful, especially if your EditText should allow diacritics (in my case, Portuguese Diacritic):
<EditText
android:digits="0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZzÁáÂâÃãÀàÇçÉéÊêÍíÓóÔôÕõÚú"
/>
A solution similar to the android:digits="0123456789*", is to use this:
EditText etext = new EditText(this);
etext.setKeyListener(DigitsKeyListener.getInstance("0123456789*"));
An added bonus is that it also displays the numeric keypad.
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start,
int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (!Character.toString(source.charAt(i)).matches("[a-zA-Z0-9-_]+")) {
return "";
edittext.setError("Only letters, digits, _ and - allowed");
}
}
return null;
}
};
edittext.setFilters(new InputFilter[] { filter });
Try this:
public static SpannableStringBuilder getErrorMsg(String estring) {
int ecolor = Color.BLACK; // whatever color you want
ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
return ssbuilder;
}
Then setError() to EditText when you want show 'only Letters and digits are allowed' as below.
etPhone.setError(getErrorMsg("Only lowercase letters and numbers are allowed!"));
Hope this will help you. I use the same for Validation Check in EditText in my apps.
please try adding the android:digits="abcde.....012345789" attribute? although the android:digits specify that it is a numeric field it does work for me to set it to accept letters as well, and special characters as well (tested on SDK-7)
You can validate this by two ways , both worked for me, hope will be helpful for you too.
1> Mentioning the chars in your edittext .
android:digits="0,1,2,3,4,5,6,7,8,9,*,qwertzuiopasdfghjklyxcvbnm,_,-"
2> Can validate pragmatically as answered by milos pragmatically
use this 2 function
public static boolean isdigit(EditText input)
{
String data=input.getText().toString().trim();
for(int i=0;i<data.length();i++)
{
if (!Character.isDigit(data.charAt(i)))
return false;
}
return true;
}
public static boolean ischar(EditText input)
{
String data=input.getText().toString().trim();
for(int i=0;i<data.length();i++)
{
if (!Character.isDigit(data.charAt(i)))
return true;
}
return false;
}
pass Edittext variable in these function .. so you can have boolean value.

How to restrict TextView to allow only alpha-numeric characters in Android

I have a TextView in my app that i want a user to be able to only enter alpha-numeric characters in. How can this be done? Thanks!
In the XML, put this:
android:digits="abcdefghijklmnopqrstuvwxyz1234567890 "
Here is a better solution......... https://groups.google.com/forum/?fromgroups=#!topic/android-developers/hS9Xj3zFwZA
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (!Character.isLetterOrDigit(source.charAt(i))) {
return "";
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});
The InputFilter solution works well, and gives you full control to filter out input at a finer grain level than android:digits. The filter() method should return null if all characters are valid, or a CharSequence of only the valid characters if some characters are invalid. If multiple characters are copied and pasted in, and some are invalid, only the valid characters should be kept (#AchJ's solution will reject the entire paste if any characters a invalid).
public static class AlphaNumericInputFilter implements InputFilter {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
// Only keep characters that are alphanumeric
StringBuilder builder = new StringBuilder();
for (int i = start; i < end; i++) {
char c = source.charAt(i);
if (Character.isLetterOrDigit(c)) {
builder.append(c);
}
}
// If all characters are valid, return null, otherwise only return the filtered characters
boolean allCharactersValid = (builder.length() == end - start);
return allCharactersValid ? null : builder.toString();
}
}
Also, when setting your InputFilter, you must make sure not to overwrite other InputFilters set on your EditText; these could be set in XML, like android:maxLength. You must also consider the order that the InputFilters are set. When used in conjunction with a length filter, your custom filter should be inserted before the length filter, that way pasted text applies the custom filter before the length filter (#AchJ's solution will overwrite all other InputFilters and only apply the custom one).
// Apply the filters to control the input (alphanumeric)
ArrayList<InputFilter> curInputFilters = new ArrayList<InputFilter>(Arrays.asList(editText.getFilters()));
curInputFilters.add(0, new AlphaNumericInputFilter());
InputFilter[] newInputFilters = curInputFilters.toArray(new InputFilter[curInputFilters.size()]);
editText.setFilters(newInputFilters);
This should work:
textView.setInputType(InputType.TYPE_CLASS_NUMBER);

How to check the value entered in EditText is aplhanumeric or not?

My application takes userid from user as input, the userid is alphanumeric i.e just the first character is (a-z), other part is numeric. How can I validate input of this type ( like G34555) ?
Use a regex. This should do it assuming the first letter can be upper or lower case:
Pattern p = Pattern.compile("[a-zA-Z][0-9]+");
Matcher m = p.matcher("some text you want");
boolean isAlphaNum = m.matches();
http://osdir.com/ml/Android-Developers/2009-11/msg02501.html seems like a more decent solution, it does not allow entering the chars that are not accepted.
Code from link:
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (!Character.isLetterOrDigit(source.charAt(i))) {
return "";
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});
I have resolved issue by using simple string function matches
String str="mystring";
str.matches("[a-zA-Z][0-9]+");

Categories

Resources