Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

I am new to android mobile development (Android Studio native development - for new knowledge). And here I want to ask a question regarding best practice for input validation. As far we know, when a developer develop input form. We need to prevent a user from key in a wrong input into the text field. So here is my question,

  1. Can we create one java file for validation purpose only? All input form ,must go to that one validation file only (In case of many input page screen in one apps). If YES, how can I get an example/link/tutorial of that technique for my learning study. If NO, why?

From my point of view personally, it should have a way to implement the technique. So that we didn't need to reuse same code all over again for each java file (in term of clean code). Unfortunately, I didn't find any example or tutorial for that. Maybe I search a wrong keyword or misread. And if there is no such technique exist, what are the best practice for input validation?

Thank you.

p/s: This thread for find a better way in best practice. Thank you.

share|improve this question
    
Actually there are some libs already github.com/vekexasia/android-edittext-validator and github.com/thyrlian/AwesomeValidation – Neil 7 hours ago

3 Answers 3

This java class implement text watcher to watch your edit text if its given any change to the text

public abstract class TextValidator implements TextWatcher {
    private final TextView textView;

    public TextValidator(TextView textView) {
        this.textView = textView;
    }

    public abstract void validate(TextView textView, String text);

    @Override
    final public void afterTextChanged(Editable s) {
        String text = textView.getText().toString();
        validate(textView, text);
    }

    @Override
    final public void beforeTextChanged(CharSequence s, int start, int count, int after) { /* Don't care */ }

    @Override
    final public void onTextChanged(CharSequence s, int start, int before, int count) { /* Don't care */ }
}

And in your edit text, you can set that text watcher to its listener

editText.addTextChangedListener(new TextValidator(editText) {
    @Override public void validate(TextView textView, String text) {
       /* Validation code here */
    }
});
share|improve this answer

Yes, you can create a class / Java file specifically for containing methods relating to checking validity of Strings. That class could contain static methods taking a String as input, and returning a boolean whether or not the String is valid. This would be a good practice if you needed to call the same validation method for multiple inputs, and if you have multiple validation methods.

example:

class StringValidation {

    public static boolean validateLogin(String text) {
       if (text.contains("@")) {
         return true;
       } else {
         return false;
       }
    }

}
share|improve this answer
    
I was going to delete this as Randyka provided a much more Android-oriented answer, but I decided to keep this as it provides a more general answer to what was a fairly vague question. – RogueBaneling 6 hours ago

One approach (which I am using) is you should have a helper for validating inputs such as:

  1. Nullity (or emptiness)
  2. Dates
  3. Passwords
  4. Emails
  5. Numerical values
  6. and others

here's an exerpt from my ValidationHelper class:

public class InputValidatorHelper {
    public boolean isValidEmail(String string){
        final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(string);
        return matcher.matches();
    }

    public boolean isValidPassword(String string, boolean allowSpecialChars){
        String PATTERN;
        if(allowSpecialChars){
            //PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})";
            PATTERN = "^[a-zA-Z@#$%]\\w{5,19}$";
        }else{
            //PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})";
            PATTERN = "^[a-zA-Z]\\w{5,19}$";
        }



        Pattern pattern = Pattern.compile(PATTERN);
        Matcher matcher = pattern.matcher(string);
        return matcher.matches();
    }

    public boolean isNullOrEmpty(String string){
        return TextUtils.isEmpty(string);
    }

    public boolean isNumeric(String string){
        return TextUtils.isDigitsOnly(string);
    }

    //Add more validators here if necessary
}

Now the way I use this class is this:

InputValidatorHelper inputValidatorHelper = new InputValidatorHelper();
StringBuilder errMsg = new StringBuilder("Unable to save. Please fix the following errors and try again.\n");
//Validate and Save
boolean allowSave = true;
if (user.getEmail() == null && !inputValidatorHelper.isValidEmail(user_email)) {
    errMsg.append("- Invalid email address.\n");
    allowSave = false;
}

if (inputValidatorHelper.isNullOrEmpty(user_first_name)) {
    errMsg.append("- First name should not be empty.\n");
    allowSave = false;
}

if(allowSave){
    //Proceed with your save logic here
}

You can call your validation by using TextWatcher which is attached via EditText#addTextChangedListener

example:

txtName.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        //Do nothing
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        validate();
    }
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.