I need to have following password validations :
At least Min Characters 8 and Maximum Characters 15
At least One Number and 1 special characters from (! ##$%^&*-=+?.);
At least One lower case letter
Password shouldn't be sub strings of username and email (min length 3 and max length 15).
Password should be case sensitive.
I have also looked these answers but I am confuse , should I use Input filters to achieve this or Regex?
Any help will be appreciable. It will be great if you guyz provide a working solution.
public class Validation {
public static void main(String[] args) {
String pass = "1AB%CDef555";
String username = "manna";
String email = "mannx#rtt.com";
System.out.println(validiate2(pass, username,email));
}
// if you don't care why it fails and only want to know if valid or not
public static boolean validiate (String pass, String username, String email){
String pattern = "^(?=.*[0-9])(?=.*[a-z])(?=.*[!##$%^&*+=?-]).{8,15}$";
if(pass.matches(pattern)){
for(int i=0;(i+3)<username.length();i++){
if(pass.contains(username.substring(i,i+3)) || username.length()<3 || username.length()>15){
return false;
}
}
for(int i=0;(i+3)<email.length();i++){
if(pass.contains(email.substring(i,i+3)) || email.length()<3 || email.length()>15){
return false;
}
}
return true;
}
return false;
}
// if you want to know which requirement was not met
public static boolean validiate2 (String pass, String username, String email){
if (pass.length() < 8 || pass.length() >15 ){
System.out.println("pass too short or too long");
return false;
}
if (username.length() < 3 || username.length() >15 ){
System.out.println("username too short or too long");
return false;
}
if (!pass.matches(".*\\d.*")){
System.out.println("no digits found");
return false;
}
if (!pass.matches(".*[a-z].*")) {
System.out.println("no lowercase letters found");
return false;
}
if (!pass.matches(".*[!##$%^&*+=?-].*")) {
System.out.println("no special chars found");
return false;
}
if (containsPartOf(pass,username)) {
System.out.println("pass contains substring of username");
return false;
}
if (containsPartOf(pass,email)) {
System.out.println("pass contains substring of email");
return false;
}
return true;
}
private static boolean containsPartOf(String pass, String username) {
int requiredMin = 3
for(int i=0;(i+requiredMin)<username.length();i++){
if(pass.contains(username.substring(i,i+requiredMin))){
return true;
}
}
return false;
}
}
There is great library for that.
It's uses anotations for field and has rich customatization.
I think that #4 still needs to be done by hand but you should definitly check out the library.
Here's the example from github:
#Password(min = 6, scheme = Password.Scheme.ALPHA_NUMERIC_MIXED_CASE_SYMBOLS)
private EditText passwordEditText;
Cheers.
You can try this one:
^(?!.*(user|emailaddress))(?=.*\d)(?=.*[! ##$%^&*=+?.-])(?=.*[a-z]).{8,15}$
Make sure you replace the user and emailaddress by your variable
Explanation
This code works fine for me:
public class NewClass1 {
public static void main(String[] args) {
NewClass1 nc = new NewClass1();
nc.check("abcd123-", "userName", "abc#yahoo.com");
nc.check("userName1-", "userName", "abc#y.c");
nc.check("abc#y.c1b", "userName", "abc#y.c");
nc.check("abcy.c1b", "userName", "abc#y.c");
nc.check("abcd123-", "userName", "abc#yahoo.com");
}
public void check(String string, String userName, String email) {
final String regex = "^(?!.*(" + userName + "|" + email + "))(?=.*\\d)(?=.*[! ##$%^&*=+?.-])(?=.*[a-z]).{8,15}$";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
if (matcher.find()) {
System.out.println(string + "Full match: " + matcher.group(0));
} else {
System.out.println("no match");
}
}
}
Related
I need to test a method that takes an input TextFild, how can I change the input to ArrayList to get the data. I am getting an error that says
java.lang.ClassCastException: class java.lang.Character cannot be cast to class
private boolean validatePassword() {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,15})");
Matcher matcher = p.matcher(passwordField.getText());
if (matcher.matches()) {
return true;
} else {
lblMessage.setText("Please enter a valid password \n" +
"(at least one uppercase, lowercase and 8 or more characters ");
return false;
}
}
my solution
public class TestCases {
ArrayList<Character> characters = new ArrayList<>();
public boolean validatePassword() {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,15})");
for (int i = 0; i < characters.size(); i++) {
Object j = characters.get(i);
Matcher matcher = p.matcher((CharSequence) j);
if (matcher.matches()) {
return true;
} else {
System.out.println(
"Please enter a valid password \n" +
"(at least one uppercase, lowercase and 8 or more characters "););
return false;
}
}
return false;
}
public void setEmail(ArrayList<Character> list) {
characters = list;
}
}
Junit class
#Test
void test() {
String password= "Kd123456";
ArrayList<Character> paswordField=new ArrayList<>();
for(int i= 0 ; i<password.length(); i++){
paswordField.add(password.charAt(i));
}
TestCases valid= new TestCases();
valid.setEmail(paswordField);
assertEquals(true,valid.validatePassword());
}
}
if hope this will help you !!
import static org.junit.Assert.assertEquals;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
public class TestCases {
public boolean validatePassword(String s) {
Pattern p = Pattern.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-z0-9 ]).{8,15})",
Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher(s);
if (matcher.matches()) {
return true;
} else {
System.out.println("Please enter a valid password \n"
+ "(at least one uppercase, lowercase and 8 or more characters ");
return false;
}
}
#Test
public void test() {
String password = "Kd12#3456";
TestCases valid = new TestCases();
assertEquals(true, valid.validatePassword(password));
}
}
I'm looking to set a validation condition for email whereby after ".xxx" (email termination, e.g: john123#gmail.xxx) the char limit is less than 3 but more than 2 only (e.g: invalid if john123#gmail.c or #gmail.commm).
here is my attempt:
public final boolean validEmail(String target){
boolean valid_dot_com
if(target.toString().contains(".")){
int indexDot = target.toString().indexOf(".");
// substring from char containing "." to last char
String temp = target.toString().substring(indexDot,
target.length());
if(temp.length()<2 && temp.length()>3){
valid_dot_com = false;
}
}
return valid_dot_com && Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
However, this code does not return the result that I needed.
I do have the theory that the Patterns.EMAIL_ADDRESS overwrite my boolean value causing the condition checking to become true even when its not.
Do enlighten me!
Edit:
I've found my answer!
through an online regex generator: https://regex101.com/
I have been able to generate a custom regex pattern to compile and do my validation. Rest of the code is similar to just simple conditions.
Thanks all for the reply!
try this custom pattern
String EMAIL_PATTERN = "^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$";
public final boolean validateEmail(String target) {
if (target !=null && target.length() > 1) {
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(target);
return matcher.matches();
} else if (target.length() == 0) {
return false;
} else {
return false;
}
}
You can use inbuilt fucntion.
if (!Patterns.EMAIL_ADDRESS.matcher(et_email.getText().toString()).matches())
{
your code.
}
Use this:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
Please refer link
try this one validate method
public static final Pattern VALID_EMAIL_ADDRESS_REGEX =
Pattern.compile("^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
public static boolean validate(String emailStr) {
Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);
return matcher.find();
}
Use this
!TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches()
pass your email string to validate to this function below, and it will return boolean either it is valid or not
public static boolean isEmailValid(String email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
The following will validate email.
public static boolean validateEmail(String email) {
Pattern emailPattern = Pattern.compile(".+#.+\\.[a-z]+");
Matcher emailMatcher = emailPattern.matcher(email);
return emailMatcher.matches();
}
Try This One
public final boolean validEmail(String target) {
Log.d("RESULT", "----------------------------------Receieved: " + target);
Log.d("RESULT", "----------------------------------String Length: " + target.length());
Log.d("RESULT", "----------------------------------Index of Dot: " + target.toString().indexOf("."));
boolean valid_dot_com = true;
if (target.toString().contains(".")) {
int indexDot = target.toString().indexOf(".");
// substring from char containing "." to last char
String temp = target.toString().substring(indexDot + 1,
target.length());
Log.d("RESULT", "----------------------------------Sub String : " + temp);
Log.d("RESULT", "----------------------------------Sub String Lenght : " + temp.length());
if ((temp.length() > 3)) {
valid_dot_com = false;
}
}
return valid_dot_com && Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
Already Answered Here
public final static boolean isValidEmail(CharSequence target) {
return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
This splits the email string using dot as a delimiter, and gets 2nd string value (at index 1 as it starts from 0) and compares it to check if its 3 or less and greater than 1 after dot.
String st = email.split("\\.")[1];
if(st.length() <=3 && st.length() > 1) {
// its 3 or less but greater than 1 after dot .
}
I'm trying to run a check whether or not a user has entered the #gmail.com suffix to their input. If not, then append it. I'm having a little difficulty because this loop seems to be written correctly to me. I'm at a loss. Anyone? I'm sure it's simple, I just can't see it.
String UN;
Scanner sc = new Scanner(System.in);
String suf = "#gmail.com";
boolean sufd;
// your code goes here
UN = sc.nextLine(); //
if(UN.length() >= 11){
sufd = UN.substring(UN.length()-11,UN.length()-1).equals("#gmail.com");
if(!sufd) {
UN += suf;
}
} else if(UN.length() < 11) {
UN += suf;
}
System.out.print(UN);
Using the official java email package is the easiest:
public static boolean isValidEmailAddress(String email) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}
public boolean isValidEmailAddress(String email) {
String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
java.util.regex.Matcher m = p.matcher(email);
return m.matches();
}
Test Cases:
.
I have an assignment that requires me to create a password checking program.
The password must be at least 8 characters, contain both capital and lower case letters, a digit and a special character.
I believe I am close to solving this problem but my skills are still developing and I've hit a wall.
package project1;
/**
*
* #author danechristian
*/
import java.util.*;
public class Project1
{
static Scanner console = new Scanner(System.in);
static final String SPECIAL_CHARACTERS = "!,#,$,%,^,&,*,|";
static String password;
public static void main(String[] args)
{
System.out.println("Create a password: ");
password = console.next();
if (validPassword(password))
{
System.out.println("Password Saved");
}
else
{
System.out.println("Invalid Passowrd. Password "
+ "must contain atleast 1 capital letter"
+ "1 lower case letter, 1 digit, 1"
+ "special character (!#$%^&*|) and "
+ "be atleast 8 characters long");
}
}
public static boolean validPassword(String password)
{
boolean upCase = false;
boolean loCase = false;
boolean isDigit = false;
boolean spChar = false;
if (password.length() >= 8)
{
for (int i = 0; i < password.length() - 1; i++)
{
if (Character.isUpperCase(password.charAt(i)))
{
upCase = true;
}
if (Character.isLowerCase(password.charAt(i)))
{
loCase = true;
}
if (Character.isDigit(password.charAt(i)))
{
isDigit = true;
}
if (SPECIAL_CHARACTERS.contains(password))
{
spChar = true;
}
}
}
return (upCase && loCase && isDigit && spChar);
}
}
In order to check have something like this:
public static boolean validPassword(String password){
boolean upCase = false;
boolean loCase = false;
boolean isDigit = false;
boolean spChar = false;
if (password.length()>7){
if (password.matches(".+[A-Z].+")){
upCase = true;
}
if (password.matches(".+[a-z].+")){
loCase = true;
}
if (password.matches(".+[1-9].+")){
isDigit = true;
}
if (SPECIAL_CHARACTERS.contains(password)){
spChar = true;
}
}
return (upCase && loCase && isDigit && spChar);
}
solved by changing
if (SPECIAL_CHARACTERS.contains(password)){
spChar = true;
to
if (SPECIAL_CHARACTERS.contains(password.substring(i,i+1))){
spChar = true;
this checks for the string within the string.
also, I removed the "- 1" from my for statement so that the bounds were corrects. also removed the commas from the SPECIAL_CHARACTERS constant.
the program now runs without issue, thanks for the advice everyone.
How can I check to see if a String contains a whitespace character, an empty space or " ". If possible, please provide a Java example.
For example: String = "test word";
For checking if a string contains whitespace use a Matcher and call its find method.
Pattern pattern = Pattern.compile("\\s");
Matcher matcher = pattern.matcher(s);
boolean found = matcher.find();
If you want to check if it only consists of whitespace then you can use String.matches:
boolean isWhitespace = s.matches("^\\s*$");
Check whether a String contains at least one white space character:
public static boolean containsWhiteSpace(final String testCode){
if(testCode != null){
for(int i = 0; i < testCode.length(); i++){
if(Character.isWhitespace(testCode.charAt(i))){
return true;
}
}
}
return false;
}
Reference:
Character.isWhitespace(char)
Using the Guava library, it's much simpler:
return CharMatcher.WHITESPACE.matchesAnyOf(testCode);
CharMatcher.WHITESPACE is also a lot more thorough when it comes to Unicode support.
This will tell if you there is any whitespaces:
Either by looping:
for (char c : s.toCharArray()) {
if (Character.isWhitespace(c)) {
return true;
}
}
or
s.matches(".*\\s+.*")
And StringUtils.isBlank(s) will tell you if there are only whitepsaces.
Use Apache Commons StringUtils:
StringUtils.containsWhitespace(str)
public static void main(String[] args) {
System.out.println("test word".contains(" "));
}
You could use Regex to determine if there's a whitespace character. \s.
More info of regex here.
Use this code, was better solution for me.
public static boolean containsWhiteSpace(String line){
boolean space= false;
if(line != null){
for(int i = 0; i < line.length(); i++){
if(line.charAt(i) == ' '){
space= true;
}
}
}
return space;
}
You can use charAt() function to find out spaces in string.
public class Test {
public static void main(String args[]) {
String fav="Hi Testing 12 3";
int counter=0;
for( int i=0; i<fav.length(); i++ ) {
if(fav.charAt(i) == ' ' ) {
counter++;
}
}
System.out.println("Number of spaces "+ counter);
//This will print Number of spaces 4
}
}
String str = "Test Word";
if(str.indexOf(' ') != -1){
return true;
} else{
return false;
}
Maybe I'm late with the most updated answer. You can use one of the following solution:
public static boolean containsWhiteSpace(final String input) {
if (isNotEmpty(input)) {
for (int i = 0; i < input.length(); i++) {
if (Character.isWhitespace(input.charAt(i)) || Character.isSpaceChar(input.charAt(i))) {
return true;
}
}
}
return false;
}
or
public static boolean containsWhiteSpace(final String input) {
return CharMatcher.whitespace().matchesAnyOf(input);
}
import java.util.Scanner;
public class camelCase {
public static void main(String[] args)
{
Scanner user_input=new Scanner(System.in);
String Line1;
Line1 = user_input.nextLine();
int j=1;
//Now Read each word from the Line and convert it to Camel Case
String result = "", result1 = "";
for (int i = 0; i < Line1.length(); i++) {
String next = Line1.substring(i, i + 1);
System.out.println(next + " i Value:" + i + " j Value:" + j);
if (i == 0 | j == 1 )
{
result += next.toUpperCase();
} else {
result += next.toLowerCase();
}
if (Character.isWhitespace(Line1.charAt(i)) == true)
{
j=1;
}
else
{
j=0;
}
}
System.out.println(result);
Use org.apache.commons.lang.StringUtils.
to search for whitespaces
boolean withWhiteSpace = StringUtils.contains("my name", " ");
To delete all whitespaces in a string
StringUtils.deleteWhitespace(null) = null
StringUtils.deleteWhitespace("") = ""
StringUtils.deleteWhitespace("abc") = "abc"
StringUtils.deleteWhitespace(" ab c ") = "abc"
I purpose to you a very simple method who use String.contains:
public static boolean containWhitespace(String value) {
return value.contains(" ");
}
A little usage example:
public static void main(String[] args) {
System.out.println(containWhitespace("i love potatoes"));
System.out.println(containWhitespace("butihatewhitespaces"));
}
Output:
true
false
package com.test;
public class Test {
public static void main(String[] args) {
String str = "TestCode ";
if (str.indexOf(" ") > -1) {
System.out.println("Yes");
} else {
System.out.println("Noo");
}
}
}