Last active
February 26, 2018 20:43
-
-
Save ntakouris/c1cf771bc3545b281b11c76b12bc7647 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
@ValidComponent | |
AutoValidatedTextInputEditText usernameEditText; | |
@ValidComponent | |
AutoValidatedTextInputEditText birthdateEditText; | |
Button submit; | |
/* ... snip ... */ | |
final static String userFriendlyBirthdayDateFormat = "MM/dd/yy"; | |
final static SimpleDateFormat userFriendlyBirthdayDateFormatter = new SimpleDateFormat(userFriendlyBirthdayDateFormat); | |
//Somewhere inside onCreate | |
usernameEditText = ... | |
birthdateEditText = ... | |
usernameEditText.addValidators(UsernameValidator.getInstance()); | |
birthdateEditText.addValidators(new DateValidator(userFriendlyBirthdayDateFormat)); | |
birthdateEditText.setOnClickListener(v -> { | |
DatePickerDialog.OnDateSetListener dateSelectedListener = (view, year, monthOfYear, dayOfMonth) -> { | |
/* Setup date listener */ | |
}; | |
/* Setup date picked callback */ | |
// When date is picked, set birthdateEditText to have the picked date, as a friendly user format | |
}; | |
); | |
submit = ... | |
final Calendar currentCalendarInUTC = Calendar.getInstance(TimeZone.getTimeZone("UTC")); | |
submit.setOnClickListener(v -> { | |
ComponentValidator.Response validationResponse = ComponentValidator.getInstance().validate(this); | |
if (!validationResponse.isValid()) { | |
validationResponse.firstInvalidComponent().requestFocus(); | |
VirtualKeyboardManager.showVirtualKeyboard(_activity); | |
return; | |
} | |
/* Continue with submit logic */ | |
}); | |
private class UsernameValidator implements TextValidator { | |
private static final UsernameValidator _instance; | |
static { | |
_instance = new UsernameValidator(); | |
} | |
private UsernameValidator() { | |
} | |
public static UsernameValidator getInstance() { | |
return _instance; | |
} | |
@Override | |
public String validate(String content) { | |
return content.matches("^[a-zA-Z0-9_.]+") ? null : "Usernames should contain alphanumeric characters, underscores & periods only"; | |
} | |
} | |
public class DateValidator implements TextValidator { | |
SimpleDateFormat sdf; | |
public DateValidator(String format) { | |
this.sdf = new SimpleDateFormat(format); | |
} | |
public DateValidator(SimpleDateFormat sdf) { | |
this.sdf = sdf; | |
} | |
@Override | |
public String validate(String content) { | |
try { | |
sdf.parse(content); | |
return null; | |
} catch (ParseException e) { | |
} | |
return "Invalid date format"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment