how to do form validation in android - android

I have a registration form which I need to validate before submit. The form has the following fields:name,email, contact number and password. I need the name to have a value, the email to have the correct format,contact number should be numbers at least 10 numbers and the password to be at least 6 characters.

try this
vUsername = etUsername.getText().toString();
vFirstname = etFirstname.getText().toString();
vEmail = etEmail.getText().toString();
vPwd = etPwd.getText().toString();
vCpwd = etCpwd.getText().toString();
if("".equalsIgnoreCase(vUsername) //vUsername.equalsIgnoreCase("") could lead to NPE
|| "".equalsIgnoreCase(vFirstname)
|| "".equalsIgnoreCase(vEmail)
|| "".equalsIgnoreCase(vPwd)
|| "".equalsIgnoreCase(vCpwd) )
{
Toast.makeText(userRegistration.this, "All Fields Required.",
Toast.LENGTH_SHORT).show();
}
checkemail(vEmail);
if(emailcheck==true)
{
// your code here
}
public void checkemail(String email)
{
Pattern pattern = Pattern.compile(".+#.+\\.[a-z]+");
Matcher matcher = pattern.matcher(email);
emailcheck = matcher.matches();
}

Alternatively, you can use a validation library to perform your validations on Android. It is driven by annotation and thereby it reduces a lot of boiler-plate code. Your use case when solved using this app would look like the following:
#Required(order = 1)
#Email(order = 2)
private EditText emailEditText;
#Password(order = 3)
#TextRule(order = 4, minLength = 6, message = "Enter at least 6 characters.")
private EditText passwordEditText;
#ConfirmPassword(order = 5)
private EditText confirmPasswordEditText;
#Checked(order = 6, message = "You must agree to the terms.")
private CheckBox iAgreeCheckBox;
There is a dearth of documentation now but the annotation example on the home page should get you started. You can also read this blog on how to create custom rules in case the stock rules do not fit your needs.
PS: I am the author of this library.

You can use the default Android validation API.
Here is a very simple tutorial: http://blog.donnfelker.com/2011/11/23/android-validation-with-edittext/
The key is to use the setError method on your EditText. It will trigger default validation UI with provided error text.

for validation of edittext, use android:inputtype, android:maxLength.
Apart from this, can use regex for validation of form

You have two possibilities:
listen to changes to the field's content and run validation of that specific field or
listen to the submit-button click and validate the content of all fields on submit.
Else validation is just the same as in every other Java app: just test your constraints.
BTW: your question was already answered on stackoverflow.

try this
if(phone.getText().toString().isEmpty()){
if(phone.lenth <= 10){
}else{ // phone is`t correct }
phone.setError("phone number is empty ");
phone.requestFocus();
return;
}
if(password.getText().toString().isEmpty()){
if(password.lenth <= 6){
}else{ // password is`t correct }
password.setError("password number is empty ");
password.requestFocus();
return;
}

Related

How to Validate Phone Number format

i am about to create a validation for phone number format..The format is 10 digit including the plus sign eg:+0133999504. Even though I have declare the pattern which is I try to disallow the "-" symbol or any other characters, but the validation is not working. Any other Idea or solution?
1st I declared the string regex:
String PhoneNo;
String PhoneNo_PATTERN ="[\\+]\\d{3}\\d{7}";
2nd I make a if..else statement:
{
Pattern pattern = Pattern.compile(PhoneNo_PATTERN);
Matcher matcher = pattern.matcher(PhoneNo);
if (!matcher.matches())
{
inputemergencyContactNo.setError("Please enter Emergency Contact No");
}
else{
Toast.makeText(RiderProfile.this, "Please filled in All field", Toast.LENGTH_SHORT).show();
}
Why not remove all non-digits and then count the digits left and put the plus back in later? This allows users the freedom to fill out their phone number anyway they want...
String PhoneNo = "+123-456 7890";
String Regex = "[^\\d]";
String PhoneDigits = PhoneNo.replaceAll(Regex, "");
if (PhoneDigits.length()!=10)
{
// error message
}
else
{
PhoneNo = "+";
PhoneNo = PhoneNo.concat(PhoneDigits); // adding the plus sign
// validation successful
}
If your app is intended for international use replace
if (!PhoneDigits.length()!=10)
with
if(PhoneDigits.length() < 6 || PhoneDigits.length() > 13)
as Fatti Khan suggested.
To apply this in the code you posted at Android EditText Validation and Regex first include this method in your public class or the class containing onClick():
public boolean validateNumber(String S) {
String Regex = "[^\\d]";
String PhoneDigits = S.replaceAll(Regex, "");
return (PhoneDigits.length()!=10);
}
And include this method in the CreateNewRider class:
protected String tidyNumber(String S) {
String Regex = "[^\\d]";
String PhoneDigits = S.replaceAll(Regex, "");
String Plus = "+";
return Plus.concat(PhoneDigits);
}
This is where the validation happens...
#Override
public void onClick(View view) {
Boolean b = false;
if(inputfullname.getText().toString().equals("")) b = true;
else if(... // do this for all fields
else if(inputmobileNo.getText().toString().equals("")) b=true;
else if(inputemergencyContactNo.getText().toString().equals("")) b=true;
else {
if(validateNumber( inputmobileNo.getText().toString() )
Toast.makeText(RiderProfile.this, "Invalid mobile number", Toast.LENGTH_SHORT).show();
else if(validateNumber( inputemergencyContactNo.getText().toString() )
Toast.makeText(RiderProfile.this, "Invalid emergency contact number", Toast.LENGTH_SHORT).show();
else {
// Validation succesful
new CreateNewRider().execute();
}
}
if(b) Toast.makeText(RiderProfile.this, "Please filled in All field", Toast.LENGTH_SHORT).show();
}
And then use tidyNumber() in the CreateNewRider class:
protected String doInBackground(String... args) {
String fullname= inputfullname.getText().toString();
String IC= inputIC.getText().toString();
String mobileNo= tidyNumber( inputmobileNo.getText().toString() );
String emergencyContactName= inputemergencyContactName.getText().toString() );
String emergencyContactNo= tidyNumber( inputemergencyContactNo.getText().toString() );
...
Given the rules you specified:
upto length 13 and including character + infront.
(and also incorporating the min length of 10 in your code)
You're going to want a regex that looks like this:
^\+[0-9]{10,13}$
With the min and max lengths encoded in the regex, you can drop those conditions from your if() block.
Off topic: I'd suggest that a range of 10 - 13 is too limiting for an international phone number field; you're almost certain to find valid numbers that are both longer and shorter than this. I'd suggest a range of 8 - 20 to be safe.
[EDIT] OP states the above regex doesn't work due to the escape sequence. Not sure why, but an alternative would be:
^[+][0-9]{10,13}$
[EDIT 2] OP now adds that the + sign should be optional. In this case, the regex needs a question mark after the +, so the example above would now look like this:
^[+]?[0-9]{10,13}$
For Valid Mobile You need to consider 7 digit to 13 digit because some country have 7 digit mobile number . Also we can not check like mobile number must starts with 9 or 8 or anything..
For mobile number I used this this Function
private boolean isValidMobile(String phone2)
{
boolean check;
if(phone2.length() < 6 || phone2.length() > 13)
{
check = false;
txtPhone.setError("Not Valid Number");
}
else
{
check = true;
}
return check;
}
^[\\+]\\d{3}\\d{7}$
Use anchors to limit the match.
^ => start of match
$=> end of match
To validate India's mobile number.
Your edit text input
edt_mobile.text.toString().trim()
Number validation method
fun isValidMobile(phone: String): Boolean {
return phone.matches(Constants.REGEX_MOBILE.toRegex()) && phone.trim().length == 10
}
Regression expression
const val REGEX_MOBILE = "^[6-9]{1}[0-9]{9}\$"

Regular Expression In Android for Password Field

How can i validating the EditText with Regex by allowing particular characters .
My condition is :
Password Rule:
One capital letter
One number
One symbol (#,$,%,&,#,) whatever normal symbols that are acceptable.
May I know what is the correct way to achieve my objective?
Try this may helps
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{4,}$
How it works?
^ # start-of-string
(?=.*[0-9]) # a digit must occur at least once
(?=.*[a-z]) # a lower case letter must occur at least once
(?=.*[A-Z]) # an upper case letter must occur at least once
(?=.*[##$%^&+=]) # a special character must occur at least once you can replace with your special characters
(?=\\S+$) # no whitespace allowed in the entire string
.{4,} # anything, at least six places though
$ # end-of-string
How to Implement?
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = (EditText) findViewById(R.id.edtText);
Button btnCheck = (Button) findViewById(R.id.btnCheck);
btnCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (isValidPassword(editText.getText().toString().trim())) {
Toast.makeText(MainActivity.this, "Valid", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "InValid", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean isValidPassword(final String password) {
Pattern pattern;
Matcher matcher;
final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{4,}$";
pattern = Pattern.compile(PASSWORD_PATTERN);
matcher = pattern.matcher(password);
return matcher.matches();
}
}
And for the Kotlin lovers :
fun isValidPassword(password: String?) : Boolean {
password?.let {
val passwordPattern = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{4,}$"
val passwordMatcher = Regex(passwordPattern)
return passwordMatcher.find(password) != null
} ?: return false
}
None of the above worked for me.
What worked for me:
fun isValidPasswordFormat(password: String): Boolean {
val passwordREGEX = Pattern.compile("^" +
"(?=.*[0-9])" + //at least 1 digit
"(?=.*[a-z])" + //at least 1 lower case letter
"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white spaces
".{8,}" + //at least 8 characters
"$");
return passwordREGEX.matcher(password).matches()
}
Source: Coding in Flow
Hope it helps someone.
Try this.
(/^(?=.*\d)(?=.*[A-Z])([#$%&#])[0-9a-zA-Z]{4,}$/)
(/^
(?=.*\d) //should contain at least one digit
(?=.*[#$%&#]) //should contain at least one special char
(?=.*[A-Z]) //should contain at least one upper case
[a-zA-Z0-9]{4,} //should contain at least 8 from the mentioned characters
$/)
try {
if (subjectString.matches("^(?=.*[#$%&#_()=+?»«<>£§€{}\\[\\]-])(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).*(?<=.{4,})$")) {
// String matched entirely
} else {
// Match attempt failed
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
(?=.*[#\$%&#_()=+?»«<>£§€{}.[\]-]) -> must have at least 1 special character
(?=.*[A-Z]) -> Must have at least 1 upper case letter
(?=.*[a-z]) -> Must have at least 1 lower case letter
(?=.*\\d) -> Must have at least 1 digit
(?<=.{4,})$") -> Must be equal or superior to 4 chars.
As an addition to the answers already given, I would suggest a different route for identifying special characters and also would split up the check for the different rules.
First splitting it up: Instead of making one big rule, split it and check every rule separately, so that you are able to provide feedback to the user as to what exactly is wrong with his password. This might take a bit longer but in something like a password checkup this will not be noticable. Also, this way the conditions are more readable.
Secondly, instead of checking for a list of special characters, you could flip it and check if the password contains any characters that are neither letters of the latin alphabet (a-zA-Z) nor digits (0-9). That way you don't "forget" special characters. For example, lets say you check specifically but in your check you forget a character like "{”. With this approach, this can't happen. You can extend that list by things you don't consider to be special characters explicitly, for example a space. In kotlin, it would look like this:
val errorText = when {
/* Rule 1 */
!password.contains(Regex("[A-Z]")) -> "Password must contain one capital letter"
/* Rule 2 */
!password.contains(Regex("[0-9]")) -> "Password must contain one digit"
/* Rule 3, not counting space as special character */
!password.contains(Regex("[^a-zA-Z0-9 ]")) -> "Password must contain one special character"
else -> null
}
Depending on your encoding, you can also use regex and define your special characters using ranges of hex codes like
Reges("[\x00-\x7F]")
I'm too late to answer but still it may help you.
I've worked with Kotlin.
Add following function.
private fun isValidPassword(password: String): Boolean {
val pattern: Pattern
val matcher: Matcher
val specialCharacters = "-#%\\[\\}+'!/#$^?:;,\\(\"\\)~`.*=&\\{>\\]<_"
val PASSWORD_REGEX = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[$specialCharacters])(?=\\S+$).{8,20}$"
pattern = Pattern.compile(PASSWORD_REGEX)
matcher = pattern.matcher(password)
return matcher.matches()
}
Function description:
(?=.*[0-9]) # a digit must occur at least once
(?=.*[a-z]) # a lower case letter must occur at least once
(?=.*[A-Z]) # an upper case letter must occur at least once
(?=.[-#%[}+'!/#$^?:;,(")~`.=&{>]<_]) # a special character must occur at least once
replace with your special characters
(?=\S+$) # no whitespace allowed in the entire string .{8,} #
anything, at least six places though
You can modify it as needed.
Hope it helps.
you can use the class Patern than Matcher for every checking format.
I give you an exemple of use :
Pattern pattern = Pattern.compile(".+#.+\\.[a-z]+");
Matcher matcher = pattern.matcher(myEmailString);
if (!myEmailString.contains("#") || !matcher.matches()) {
// error in the email : do staff
myEmailView.setError("invalid email !");
}
All of the other answers are good, but the implementation of special characters were a bit too messy for my taste. I used Unicode for special characters instead.
I used special characters specified in the OWASP website.
Kotlin:
val SPECIAL_CHARACTERS_REGEX =
"?=.*[\\u0020-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]"
val PASSWORD_REGEX =
"^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])($SPECIAL_CHARACTERS_REGEX).{8,}\$"
fun isValidPassword(password: String) = Pattern.matches(PASSWORD_REGEX, password)
Most common password validation is
At least 8 character
Require numbers
Require special character
Require uppercase letters
Require lowercase letters
Regex:
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\\\/%§"&“|`´}{°><:.;#')(#_$"!?*=^-]).{8,}$
Kotlin code:
val PASSWORD_REGEX_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\\\/%§"&“|`´}{°><:.;#')(#_$"!?*=^-]).{8,}$"
fun isValidPassword(password: String?): Boolean {
val pattern: Pattern =
Pattern.compile(PASSWORD_REGEX_PATTERN)
val matcher: Matcher = pattern.matcher(password)
return matcher.matches()
}
online regex validator to check it:
https://regex101.com/
https://www.freeformatter.com/java-regex-tester.html#ad-output
private fun passwordValidate(password1: String, password2: String): Boolean {
when {
password1.length < 9 -> {
textView2.text = "Password Has To Be At Least 9 Characters Long"
return false
}
!password1.matches(".*[A-Z].*".toRegex()) -> {
textView2.text = "Password Must Contain 1 Upper-case Character"
return false
}
!password1.matches(".*[a-z].*".toRegex()) -> {
textView2.text = "Password Must Contain 1 Lower-case Character"
return false
}
!password1.matches(".*[!##$%^&*+=/?].*".toRegex()) -> {
textView2.text = "Password Must Contain 1 Symbol"
return false
}
password1 != password2 -> {
textView3.text = "Passwords Don't Match"
return false
}
else -> return true
Try this,
if (validatePassword())
{
// if valid
}
private boolean validatePassword() {
String passwordInput = password.getText().toString().trim();
if (!passwordInput.matches(".*[0-9].*")) {
Toast.makeText(mActivity, "Password should contain at least 1 digit", Toast.LENGTH_SHORT).show();
return false;
}
else if (!passwordInput.matches(".*[a-z].*")) {
Toast.makeText(mActivity, "Password should contain at least 1 lower case letter", Toast.LENGTH_SHORT).show();
return false;
}
else if (!passwordInput.matches(".*[A-Z].*")) {
Toast.makeText(mActivity, "Password should contain at least 1 upper case letter", Toast.LENGTH_SHORT).show();
return false;
}
else if (!passwordInput.matches(".*[a-zA-Z].*")) {
Toast.makeText(mActivity, "Password should contain a letter", Toast.LENGTH_SHORT).show();
return false;
}
else if (!passwordInput.matches( ".{8,}")) {
Toast.makeText(mActivity, "Password should contain 8 characters", Toast.LENGTH_SHORT).show();
return false;
}
else {
return true;
}
}
I have a simple way to check it without using regex in Kotlin.
It will check for password length >= 8, at least one capital letter, one small letter, one number, and one special character.
fun isValidPassword(pass:String):Boolean{
if(pass.length<8) return false
var u = 0
var l = 0
var d = 0
var s = 0
for (char in pass){
if(char.isUpperCase()) u++
else if(char.isLowerCase()) l++
else if(char.isDigit()) d++
else if(char in "##$%^&+=_.") s++
}
if(u==0|| l==0 || s==0 || d==0) return false
return true
}

password validation should accept special character, number, character but not whitespaces

I am trying to validate password field for my application. I make validation to check whether string contain spaces or not but it's not accepting special character like '#' and others.
I need to allow user to enter special character but not allow to use white spaces.
Here is my validation code.
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(oldPass);
Matcher matcher1 = pattern.matcher(newPass);
boolean found = matcher.find();
boolean found1 = matcher1.find();
if(found || found1)
{
DisplayError(Constants.PASSWORD_CANNOT_CONTAIN_SPACES);
}
Please give me any hint or reference.
update
if (newPass.indexOf(' ') != -1 || oldPass.indexOf(' ') != -1) {
DisplayError(Constants.PASSWORD_CANNOT_CONTAIN_SPACES);
}
I think it's too simple to use regular expressions.
if (password.indexOf(' ') != -1) {
// display error
}

Validation of Name in EditText

In my application I have field name. It works perfect if field contain digits or .,?... characters but when I enter usman(space)shafi it gives error. My statement take space as invalid character between two words. Please can anyone tell me how to make it work. Thanks
here is the code
if(!Pattern.matches("[a-zA-Z]+", textname.getText().toString().trim())){
textname.setError("Invalid Characters");
}
// if(!Pattern.matches("[a-zA-Z]+", textkin.getText().toString().trim())){
// textkin.setError("Invalid Characters");
// }");
Add the space to your regular expresion:
if(!Pattern.matches("[a-zA-Z ]+", textname.getText().toString().trim())){
textname.setError("Invalid Characters");
}
If it would be just a one white space inside you can try something like this:
text = textname.getText().toString().trim();
string[] txtSplt = text.split(" ");
text = "";
foreach (string s : txtSplt)
{
text += s;
}
Then you can proceed with checking the condition without changing your regex.
DO this by this way. Your problem will be solved.
String regex = "([A-Z a-z]+)";
Pattern pattern1 = Pattern.compile(regex);
Matcher matcher1 = pattern1.matcher(textname.getText().toString());
if(!matcher1.matches()){
textname.setError("Invalid Characters");
}

Format Android EditText to specific pattern

I need the user to enter text in an EditText according to this specfic pattern:
123.456-7890-123.456
The user can input any number of integers, so they could as well enter 123.456-7
I do not want the user to enter . or - just the numbers, like an input mask.
Also the numeric keyboard should only show.
I've searched StackOverflow extensively and have seen examples that use InputFilter, ChangedListener, TextWatcher but have not found anything simlar to what I'm trying to do. I've tried in various implementations of what I've found, but I'm inexperienced in using these so I may have overlooked something.
Any suggestions would be welcome.
You're going to have to use a TextWatcher and a regular expression pattern matcher to accomplish what you're trying to do.
This answer should be helpful: Android AutoCompleteTextView with Regular Expression?
You can create your own class that implements InputFilter. Then you would apply it as follows:
MyInputFilter filter = new MyInputFilter(...);
editText.setFilters(new InputFilter[]{filter});
Refer to the docs for how InputFilter is intended to work, then refer to the source code for some of the InputFilters used in Android for some ideas how to implement them.
After many failed attempts to implement InputFilter or Regular Expressions I opted for something a little more straight forward:
public void onTextChanged(CharSequence s, int start, int before, int count) {
String a = "";
String str = id.getText().toString();
String replaced = str.replaceAll(Pattern.quote("."),"");
replaced = replaced.replaceAll(Pattern.quote("-"),"");
char[] id_char = replaced.toCharArray();
int id_len = replaced.length();
for(int i = 0; i < id_len; i++) {
if(i == 2 || i == 12) {
a += id_char[i] + ".";
}
else if (i == 5 || i == 9) {
a += id_char[i] + "-";
}
else a += id_char[i];
}
id.removeTextChangedListener(this);
id.setText(a);
if(before > 0) id.setSelection(start);
else id.setSelection(a.length());
id.addTextChangedListener(this);
}
I don't know if this is the best approach but it does work. One problem I still haven't solved is how to handle cursor placement after the user deletes or inserts a number. If the user inserts the cursor somewhere in the EditText and enters a new number the cursor jumps to the end of the EditText. I would like the cursor to stay where it is at. Another problem if the user inserts the cursor within the EditText number and backspaces to delete a number, then the first key entry doesn't work and on the second key the number is entered. I can only guess this has to do with focus?
Use this: https://github.com/alobov/SimpleMaskWatcher.
Just set your mask for this watcher (###.###-####-###.###). It will add special symbols automatically and wont check your input string for being complete.
But showing the numeric keyboard you must handle by your own using android:inputType="number" tag for your EditText.

Categories

Resources