Last active
May 4, 2017 15:18
-
-
Save iamrajendra/a4e3e18d0ff3bada43e6e2dbb40af301 to your computer and use it in GitHub Desktop.
##How to add validation in android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FormActivity extends AppCompatActivity { | |
private EditText mEditText_name, mEditText_email,mEditText_mobile; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_form); | |
init_ui(); | |
} | |
private void init_ui() { | |
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); | |
setSupportActionBar(toolbar); | |
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); | |
fab.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) | |
.setAction("Action", new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
addValidation(); | |
} | |
}).show(); | |
} | |
}); | |
} | |
private void addValidation() { | |
Validation validation = new Validation(this); | |
validation.validation_email(R.id.email,"Invalid email Id"); | |
validation.validation_mobile(R.id.mobile,"Invalid mobile no "); | |
validation.validation_name(R.id.name,"Invalid name Id"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Validation { | |
private Activity mActivity; | |
public Validation(Activity activity) { | |
mActivity = activity; | |
} | |
public void validation_name(int id, String errorMessage) { | |
} | |
public void validation_mobile(int id, String errorMessage) { | |
EditText editText = (EditText) mActivity.findViewById(id); | |
if (!(editText.getText().toString().matches(Patterns.PHONE))) { | |
editText.setError(errorMessage); | |
return; | |
} | |
} | |
public void validation_email(int id, String errorMessage) { | |
EditText editText = (EditText) mActivity.findViewById(id); | |
if (!(editText.getText().toString().matches(Patterns.EMAIL_ADDRESS))) { | |
editText.setError(errorMessage); | |
return; | |
} | |
} | |
public class Patterns { | |
public static final String EMAIL_ADDRESS = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"; | |
public static final String PHONE = "[0-9]{10}"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment