I was wondering what is the best way to validate form ?
I did try the following:
EditText fname = (EditText)findViewById(R.id.first_name);
String fname_text = fname.getText().toString;
if(fname_text.equalsIgnoreCase(""))
{
fname.setError("Field is required");
}
and also:
fname.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count){
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after){
}
#Override
public void afterTextChanged(Editable s)
{
Pattern mPattern = Pattern.compile("[A-Za-z]{2,20}$");
Matcher matcher = mPattern.matcher(s.toString());
if(!matcher.matches()) // on Success
{
fname.setError("Please make sure you input a valid first name");
}
}
});
The thing that I am confused in is that ... whenever the page loads for the first time, the error message is shown, but when I go inside the EditText and type some content, and if I erase the content, the error message does not persist. So how do I keep this validation persistent ??? Because the way that the program is shaping up, it looks like it won't validate anything very nicely. And you guys know some good links for regex in android with complete example, please do recommend.
And also, how will me putting the Pattern and Matcher methods in onTextChanged or beforeTextChanged affect the output ?
Instead of running the check right after
EditText fname = (EditText)findViewById(R.id.first_name);
String fname_text = fname.getText().toString;
Use an OnFocusChangeListener and run it whenever the onFocusChange() method is called. Ideally, you'd run it only when the View loses focus. Something like:
EditText fname = (EditText)findViewById(R.id.first_name);
String fname_text = fname.getText().toString;
fname.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean arg1) {
if(!(v.isFocused())) {
//Run your validation
}
}
});
This way, you only run the Validation when the user is done typing, instead of everytime the user changes something.
Related
create tag comment system in android same as facebook.
In comment section if we insert # and type then show list of friend. and choose one friend. I want this type of comment system same as facebook.
You can set a TextWatcher which will get triggered whenever text changes in your EditText. Then, you can use a Regex after an # is found to see if there is any #name followed by a space. If there is, you can make another UI element pop up which shows a ListView of friends which match the particular Regex. Here is an example which I came up with:
// Declare listening as a member variable
commentInput.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// Listen until space
String text = charSequence.toString();
if (text.contains("#")) {
listening = true;
int index = text.split("#").length;
String textToSearchFor = text.split("#")[index];
// Use textToSearchFor to search for friends,
// and if you get results then set a UI element
// to appear: listView.setVisibility(View.VISIBLE);
// on click of ListView element, stop listening
} else if (text.substring(0, text.length() - 1).equals(" ")) {
// If the latest character is a space, then stop listening
listening = false;
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
Although code is far from being complete, for the begining I tried to detect via TextWatcher
when character is pressed in EditText that doesn't belong to hex values and not to permit it
to be displayed, but to inform user of error entry.
The excerpt from code follows, where arrayOfChars consists of 16 permitted hex chars and edt2
is EditText var. What I tried is to enter following chars: "aeyd", so it is aim to inform of
"y" as an error and not to display it.
edt2.addTextChangedListener(new TextWatcher(){
private boolean errorDetected= false;
private int oldbefore;
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String st;
if (errorDetected){ //set in code bellow
errorDetected= false;
return;
}
st= s.toString();
if (before > 0){
if (before<= s.length()){st= s.subSequence(before, s.length()).toString();}
}
boolean velid= true;
for (char c: st.toCharArray()){
if (new String(arrayOfChars).indexOf(Character.toUpperCase(c))==-1){
edt2.setError("Wrong char - " + c);
errorDetected= true;
oldbefore= before;
velid= false;
break;
}
}
if (velid) {edt2.setError(null);}
}
#Override
public void afterTextChanged(Editable s) {
if (errorDetected){s.delete(oldbefore, s.length());}
}
});
When "y" is entered everything behave as expected- only "ae" displayed and error info also.
However when "d" is entered and breakpoint settled at the beginning of onTextChanged, I see
"s" parameter to be "aeyd"- so "y" is still preserved somehow.
Any help where I go wrong ?
I cannot find a complete answer for this question so I'll put it again here. I have an EditText, which requires validation every time the user finishes editing. A lot of answers online rely on method editText.setOnEditorActionListener() to detect user pressing Done. However, this methods doesn't detect if the user presses the three hard keys (Back, Home, and the third one). I want to trust the user to always press Done but that's highly unlikely. Please help me out on this issue; and also the name of the third button.
Edit: if there is no validation in place, is there a way to revert all changes made? For example, whenever the user presses BACK, HOME or RECENTS, all changes will be gone?
Try some Like This:
String finalText;
tv = (TextView)findViewById(R.id.charCounts);
textMessage = (EditText)findViewById(R.id.textMessage);
textMessage.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
finalText= tv.getText().toString();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
public boolean methodOfValidation(String finalText){
if ( finalText.equals("myCorrectText") )
return true;
else
return false;
}
#Override
public void onDestroy()
{
super.onDestroy();
if(!methodOfValidation(finalText))
Toast.makeText(getApplicationContext(),"ERROR ERROR", toast.LENGTH_SHORT).show();
else
finish();
}
Try validating it in onDestroy and onPause.
When user press HOME (BACK), onPause (onDestroy) will be invoked. So you do something like this there
String text = myEditText.getText().toString();
if (text.equals("")) {
// The EditText is empty. Do nothing.
} else {
// Make the changes here.
}
This is the way u follow ur task.u ll easily validate ur all editText. Inside Button u have to use this.
String grpn=edittext1.getText().toString();
String star=edittext2.getText().toString();
String en=edittext13.getText().toString();
if( grph.equalsIgnoreCase("Select"))
{e`
else if(star.equalsIgnoreCase(""))
{ Toast.makeText(getApplicationContext(), "Set the date", Toast.LENGTH_LONG).show();
}
else if(en.equalsIgnoreCase(""))
{
Toast.makeText(getApplicationContext(), "Please set group no", Toast.LENGTH_LONG).show();
}`
I have a customized EditText class, whats is happening is that there is a validation already for the field, checking it's length and doing trim.
But, the app is crashing because it is possible to click in the field and insert data after 1 space.
How can I validate when clicking, that user can not write his data? If he/she writes data with one space, the app crashes and I receive the following exception.
java.lang.IllegalArgumentException: Start position must be less than the actual text length
Thanks in advance.
Either you can trim but remember this wont restrict to enter white spaces by user, If you want to restrict white spaces then you need to add filter for your edit text. Adding filter let you restrict what ever character you want to avoid.
P.S - Check for adding filter on given link How do I use InputFilter to limit characters in an EditText in Android?
add "addTextChangedListener" to your EditText and then onTextChanged you can check for your validation. For example,
txtEdit.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
String str = s.toString();
if(str.length() > 0 && str.startsWith(" ")){
Log.v("","Cannot begin with space");
txtEdit.setText("");
}else{
Log.v("","Doesn't contain space, good to go!");
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Get the edit text first by this way:
EditText name=(EditText) findViewById(R.id.txt);
String txtEdit=txt.getEditableText().toString();
then check the text length validation by:
if(txtEdit.length() == 0) {
//your code for what you want to do.
}
trim the string that you get from edit text.
String str=edtext.getText().toString().trim();
if(str!=null && !str.equalsIgnoreCase("")))
{
//perform your operations.
}
else
{
//give error message.
}
I want to create the EditText which allow Numeric Values, Comma and Delete and other values are ignore.
So How I can achieve this by programming code ?
Thanks.
I achieved same thing using follwing code, hope you will also find help from it.
editText.addTextChangedListener(controller);
#Override
public void afterTextChanged(Editable s) {
if(s.trim.length() > 0)
{
int start = s.toString().length() - 1;
int a = (int) s.charAt(start);
if (!(a >= 48 && a <= 57 || a == 44))
s = s.delete(start, start + 1);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
To restrict what characters can be typed into an android EditText, you must set them in the android:digits XML attribute. See http://developer.android.com/reference/android/widget/TextView.html#attr_android:digits . Make sure to also validate user input before putting it into storage.
just simple ,
you want to create a text-field like that you can enter the new string must have some grammar that you want to allow.
i have some email validation grammar that can help you.
string = "/alphabetics/number/special-character" ;
and another is
user-entered-string = " ";
just compare user-entered-string's lexems and you defined grammar.