Empty Field and other Validations in android [duplicate]
Is there any built-in method available in Android for validations like Email validation, empty string validation etc..??开发者_C百科
There's no built-in validation in Android, you could just use common Java helper classes, which are to be found on the web I'm sure.
You could try the apache validator lib. But if you like, I have written a very easy to understand validation library. Free to download and use.
You can find it here: Android field validation
Here a code sample:
new CheckBoxRequiredValidator(myCheckbox, "This checkbox is required"); // To validate checkboxes
new RegExpressionValidator(_armyName, getString(R.string.charRegularExpression),
getString(R.string.armyNameValidation), getString(R.string.illegalexpression)); // Regex validation
The regular expressing and the error message is in strings.xml
public class MainActivity extends AppCompatActivity {
EditText name1,address1,mobile,adhar,pincod,email_id;
Button submit,forget;
String em;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name1=(EditText)findViewById(R.id.name);
address1=(EditText)findViewById(R.id.address);
mobile=(EditText)findViewById(R.id.mobile_no);
adhar=(EditText)findViewById(R.id.adhar_no);
pincod=(EditText)findViewById(R.id.pincode);
email_id=(EditText)findViewById(R.id.email);
submit=(Button)findViewById(R.id.Submit);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intilize();
if (!validation()){
Toast.makeText(MainActivity.this,"sucessfull",Toast.LENGTH_LONG).show();
}
}
private boolean validation() {
boolean valid=true;
if (name1.getText().toString().isEmpty()||name1.getText().length()<6){
name1.setError("invalid name");
valid=false;
}
if (address1.getText().toString().isEmpty()||address1.getText().length()>10){
address1.setError("wrong address");
valid=false;
}
if (mobile.getText().length()!=10){
mobile.setError("incorrect number");
valid=false;
}
if (em.isEmpty()|| !Patterns.EMAIL_ADDRESS.matcher(em).matches()){
email_id.setError("wrong email id");
}
return true;
}
});
}
private void intilize() {
em=email_id.getText().toString();
}
}
精彩评论