Java Program - Email address verification using Strings and RegEx - java

The problem statement goes like this:
We need to create a String data type called emailId
The email ID has to be set using appropriate setter methods.
The validation rules for the email ID check have to be implemented in the main().
Conditions are:
Overall length of the email ID must be >3 and <20.
The emailId must include "#" followed by a minimum of 1 and maximum of 2 "." characters.
The substring before "#" must contain a combination of Upper Case, Lower Case and "_"(underscore) symbols.
The first letter of the email Id must be in Upper Case.
If all the above conditions are valid, it should display "Email ID is valid" or else, it should display an appropriate error message
This is my code:
public class EmailCheck {
String emailId;
public void setEmailId(String emailId){
this.emailId=emailId;
}
public String getEmailId(){
return emailId;
}
public static void main(String[] args) {
EmailCheck em = new EmailCheck();
em.setEmailId("CFDV#gm.a.il.com");
String email = em.getEmailId();
int length = email.length();
boolean flag1 = false;
boolean flag2 = false;
boolean flag3 = false;
boolean flag4 = false;
boolean flag5 = false;
boolean flag6 = false;
boolean flag7 = false;
int count = 0;
//Condition 1
if((length>3 && length<20)== true)
flag1 = true;
else
flag1 = false;
//Condition 2
int temp = email.length();
if(email.contains("#")){
flag2=true;
int a=email.indexOf("#");
for(int i=a;i<temp;i++){
if(email.charAt(i)=='.'){
flag3=true;
count=count+1;
}
}
if(count<1||count>2){
flag4=false;
}
else{
flag4=true;
}
}
else{
flag2 =false;
System.out.println("No # symbol present");
}
//Condition 3
if(email.matches("[A-Z a-z _]+#.*")) //Unable to get the right RegEx here!
flag5 = true;
else
flag5 = false;
//Condition4
if(Character.isUpperCase(email.charAt(0))==true)
flag6 = true;
else
flag6=false;
if(flag1==true && flag2==true && flag3==true && flag4==true && flag5==true &&flag6==true)
System.out.println("Email ID is valid");
else{
if(flag1==false)
System.out.println("Inavlid length of Email ID");
if(flag2==false||flag3==false||flag4==false)
System.out.println("Invalid Position of Special Characters");
if(flag5==false)
System.out.println("Invalid combination for username");
if(flag6==false)
System.out.println("Invalid case of first letter");
}
}
}
I'm not sure of the condition #2(the logic?) and condition #3(the RegExp part). A few of the test cases seem correct, the rest of them are wrong(owing to faulty logic in #2 and esp #3, I think.)
Please, tell me what changes have to be done here to get the right output.
Thanks!

If you insist on using regex you can use this but without validating properly you could be in for all kinds of trouble
static Pattern emailPattern = Pattern.compile("[a-zA-Z0-9[!#$%&'()*+,/\-_\.\"]]+#[a-zA-Z0-9[!#$%&'()*+,/\-_\"]]+\.[a-zA-Z0-9[!#$%&'()*+,/\-_\"\.]]+");
public static boolean isValidEmail(String email) {
Matcher m = emailPattern.matcher(email); return !m.matches();
}
Or alternatively you could use
public static boolean isValidEmailAddress(String email) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}
Which is a core java utility which would be better...
Note that neither of these will guarentee an address is actually valid, just that it is correctly formed and so hypothetically could exist
String email_regex = "[A-Z]+[a-zA-Z_]+#\b([a-zA-Z]+.){2}\b?.[a-zA-Z]+";
String testString = "Im_an_email#email.co.uk";
Boolean b = testString.matches(email_regex);
System.out.println("String: " + testString + " :Valid = " + b);
will check for the last three constraints which you can then combine with
string.length()>3 && string.length()<20

Overall length of the email ID must be >3 and <20.
You have this part fine - a pair of length checks. Things to consider:
You don't need if (condition == true), just if (condition).
If this fails, you can stop processing the email and just display the error. The same applies for all your other error conditions.
The emailId must include "#" followed by a minimum of 1 and maximum of 2 "." characters.
Check for the # sign first and get the index. Once you have that, you can split the string. You can then split the substring on periods and count them - you want two or three.
There's probably a regex that would do this as well.
The substring before "#" must contain a combination of Upper Case, Lower Case and "_"(underscore) symbols.
You can use this approach to ensure your regex must match each part. As it stands, I believe your regex will work if there are caps, lowercase, or an underscore instead of checking for all three.
The first letter of the email Id must be in Upper Case.
Same comments as for the first part, drop the == true and short circuit the method if it fails.

Related

Java Swing Register Form Password Weakness Conditions

I want to make a registration system in java. It's in a very good progress. I only have one specific problem. The password weakness. I made that, tha password must be longer than 8 character with a simple
if(password.getText().length() > 8) { error message }
I also put a condition just like that:
if(... < 8 || !(password.getText().contains("1"))) { error message }
But with this condition it only accept the password if your password for example: asdfghjk1
So I tried the condition with a lot of || condition like !....contains("2")..|| !..contains("9")
But with theese conditions it only works when the password is: 123456789
But what i really want to do is a password, that longer than 8 character, contains at least one capital and at least one number. Is that any way to do that?
By the way I use Java swing.
The best way to solve this problem is to use Regex. Here I am making an example for you of how to use regex to check password.
import java.util.regex.*;
class GFG {
// Function to validate the password.
public static boolean
isValidPassword(String password)
{
// Regex to check valid password.
String regex = "^(?=.*[0-9])"
+ "(?=.*[a-z])(?=.*[A-Z])"
+ "(?=.*[##$%^&+=])"
+ "(?=\\S+$).{8,20}$";
// Compile the ReGex
Pattern p = Pattern.compile(regex);
// If the password is empty
// return false
if (password == null) {
return false;
}
// Pattern class contains matcher() method
// to find matching between given password
// and regular expression.
Matcher m = p.matcher(password);
// Return if the password
// matched the ReGex
return m.matches();
}
// Driver Code.
public static void main(String args[])
{
// Test Case 1:
String str1 = "Thuans#portal20";
System.out.println(isValidPassword(str1));
// Test Case 2:
String str2 = "DaoMinhThuan";
System.out.println(isValidPassword(str2));
// Test Case 3:
String str3 = "Thuan# portal9";
System.out.println(isValidPassword(str3));
// Test Case 4:
String str4 = "1234";
System.out.println(isValidPassword(str4));
// Test Case 5:
String str5 = "Gfg#20";
System.out.println(isValidPassword(str5));
// Test Case 6:
String str6 = "thuan#portal20";
System.out.println(isValidPassword(str6));
}
}
Output:
true
false
false
false
false
false
Also you can refer to similar topics by following the link below:
Regex Java for password
You can do that by using regex, but I don't know how.
but this should work:
this is where you validate your password:
String passwordString = password.getText();
if (passwordString.Length() > 8 && checkCapital(passwordString) && checkDigit(passwordString)){ valid password }
else { error message }
this is checkCapital I used ascii codes:
private static boolean checkCapital(String string) {
for (char c : string.toCharArray()) {
int code = (int) c;
if (code >= 65 && code <= 90)
return true;
}
return false;
}
this is checkDigit:
private static boolean checkDigit(String string) {
for (int i = 0; i < 10; i++) {
if (string.contains("" + i))
return true;
}
return false;
}

Making A Password Key Validator And One Of The Output Should Show: Reports ALL The Rules That The Key Failed

I am making a Password/Key Validator with a set of rules which must be met to validate the Password/Key.
These rules are the following: - The key be at least 7 characters long, AND at most 20 characters long, AND - The key must not start with the special characters '#' or '', AND - The key must not have a space character anywhere, AND - The key must have at least one Upper case character and at least one Lower case character, AND - The key must not contain the user's name, AND - The key must contain either a '#' or a '', but not both.
I have managed to get all the rules to work. There are two outputs that checks the key against the rules and either reports that the key is valid or reports ALL the rules that the key failed.
On the output, I am unable to show/report ALL the rules that the key failed.
The code I currently have is below. I am new to learning java so please understand.
* Asks user for key word and the name and then checks if it is a valid key word.
*/
public void doCompletion(){
String key = UI.askString("Key: ");
String name = UI.askString("Your name: ");
this.validateKeyCompletion(key, name);
}
/** COMPLETION
* Report that the key is valid or report ALL the rules that the key failed.
*/
public void validateKeyCompletion(String key, String name){
/*# YOUR CODE HERE */
int characterNumber = key.length();
boolean hasUppercase;
boolean hasLowercase;
hasUppercase = !key.equals(key.toLowerCase());
hasLowercase = !key.equals(key.toUpperCase());
String specialChars = "(.*[ # _ ].*)";
if (characterNumber < 7 || characterNumber > 20){
UI.println("Invalid: Key length must not be less than 7 or greater than 20");
}
else if (key.contains(" ")){
UI.println("Invalid: Key cannot contain ' '");
}
else if(!hasUppercase)
{
UI.println("Invalid: Key must contain an uppercase character");
}
else if(!hasLowercase)
{
UI.println("Invalid: Key must contain a lowercase character");
}
else if(key.matches(name)){
UI.println("Invalid: Key cannot contain Username");
}
else if(!key.matches("^[^#_]+[#_]{1,1}[^#_]*")) {
UI.println("Invalid: Key must contain either a '#' or a '_', but not both");
}
else {
UI.println("Valid");
}
}
You're pretty close; your current solution will stop at the first failure case. Since you want to know all of the cases that fail, you need to keep all the checks separate (not in an if/else if/else if chain). But, then you need some way to remember if any of the checks have failed to determine a pass/fail at the end. It's easiest to use a boolean value (let's call it isValid for this and set to true at the beginning, and then in each if block (that gets triggered when a check has failed), set isValid to false. Then if it fails more than one time, it'll just get set to false a couple of times, but at the end you know at least one of the checks has failed.
public void validateKeyCompletion(String key, String name) {
int characterNumber = key.length();
boolean isValid = true; // use this to see if any checks have failed at the end
boolean hasUppercase;
boolean hasLowercase;
hasUppercase = !key.equals(key.toLowerCase());
hasLowercase = !key.equals(key.toUpperCase());
if (characterNumber < 7 || characterNumber > 20) {
UI.println("Invalid: Key length must not be less than 7 or greater than 20");
isValid = false; // set to false for each check that fails
}
if (key.contains(" ")) {
UI.println("Invalid: Key cannot contain ' '");
isValid = false;
}
if (!hasUppercase) {
UI.println("Invalid: Key must contain an uppercase character");
isValid = false;
}
if (!hasLowercase) {
UI.println("Invalid: Key must contain a lowercase character");
isValid = false;
}
if (key.matches(name)) {
UI.println("Invalid: Key cannot contain Username");
isValid = false;
}
if (!key.matches("^[^#_]+[#_]{1,1}[^#_]*")) {
UI.println("Invalid: Key must contain either a '#' or a '_', but not both");
isValid = false;
}
// now if isValid is true, we know all the checks passed
if(isValid) {
UI.println("Pass!");
} else {
UI.println("Fail!");
}
}

Java text filter

For a project I need to develop een Java application which checks a string on multiple parts:
First a text check if the word contains a word of a specified list.
Keep reminded that:
It is possible that the input can contain a word of the list but there can be spaces or special characters can be put in between characters to bypass the filter. In that case the filter needs to filter the word to.
It is possible that the word can be placed in another word. Then the word needs to be filtered if list the before and/or after filter is specified.
Second is filtering the text if it contains an ip address.
Keep reminded that:
It is possible that the input can contain an ip where speciale characters or spaces are used to bypass the filter. In that case the filter needs to filter the ip address to.
As third is filtering web addresses from the text.
Also here keep reminded that:
It is possible that the input can contain an web address where special characters or spaces are used to bypass the filter. In that case the filter needs to filter the web address to.
I tested some idea's with checking on spaces and speciale characters, but it cost a lot of work to proces the incoming text.
An example of what i tried:
public static boolean validateBericht(String msg) {
return validateTransformedBericht(msg);
}
private static boolean validateTransformedBericht(String bericht) {
if (bericht.length() != 0) {
for (String woord : ChatControlList.getChatControlList()
.getWoordenLijst()) {
for (int i = 0; i < (bericht.length() - (woord.length() - 1)); i++) {
if (i == 0 || inTekenLijst(bericht.charAt(i))) {
int index = 0;
for (int j = i; j < bericht.length(); j++) {
if (inTekenLijst(bericht.charAt(j))) {
} else if (bericht.charAt(j) == woord.charAt(index)) {
index++;
} else {
break;
}
if (index == woord.length()) {
if ((bericht.length() - 1) == j
|| inTekenLijst(bericht.charAt(index))) {
return true;
} else {
break;
}
}
}
}
}
}
}
return false;
}
private static boolean inTekenLijst(char teken) {
for (String tekenUitLijst : ChatControlList.getChatControlList()
.getSpecialeTekens()) {
if (tekenUitLijst.equalsIgnoreCase(String.valueOf(teken))
|| String.valueOf(teken).equalsIgnoreCase(" ")) {
return true;
}
}
return false;
}
Has someone any idea how to solve it on a good working solution?
Harm
In this case you should create two methods:
first to test if the String matches the searched word
and the second one to test the type of an address.
Then you can use them like you want in your code.
Code to check if your String matches the searched word:
String line = "the wor ld is wonderful";
String search = "wor ld";
String pattern = "(" + search + ")";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
if (m.find()) {
System.out.println("Found value: " + m.group(0));
} else {
System.out.println("NO MATCH");
}
Method that tests a given address and tells if it's an IP address; a Web address or an invalid address:
public static String testAddress(String address) {
if (address.matches("^(?:(?: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]?)$")) {
return "IP Address";
} else if (address.matches("^(http\\:\\/\\/|https\\:\\/\\/)?([a-z0-9][a-z0-9\\-]*\\.)+[a-z0-9][a-z0-9\\-]*$")) {
return "Web address";
} else {
return "invalid input";
}
}
And this is a Working Ideone Test.
For the first part, you could strip out all of the special characters and spaces, e.g.
testString = origString.replaceAll("[- #$%]", ""); //Extend the regex to add your own special characters
...and then search for the words...
containsWord = testString.toLowerCase().contains(badWord);

Using while loop to validate password in Java

The prompt is to have a user input a password and the password must be at least 8 characters with no white spaces, must have one upper case letter, and must have one digit. It has to use a while loop. If the password conforms it should output "password ok" or otherwise say "try again"
Anyone know what to do for this?
All I can pretty much do is the scanner and user input
Use 2 boolean flags. One each for checking presence of digit, uppercase letter. Your condition could go like :
//loop start
{
if(string.charAt(i)==space){
print "not valid"
return false;
}
// check for capital letter here and set flag to true if it is found.
// check digit here and set that flag to true if found.
}//loop end
// outside the loop make these checks
if(string.length>8 && isCapitalFound && isDigitFound)
//print "valid"
return true
I made your home work for you:
boolean noWhite = false;
boolean oneUppercase = false;
boolean oneDigit = false;
Scanner scan = new Scanner(System.in);
String pass = "";
while (!noWhite || !oneUppercase || !oneDigit || pass.length() < 8) {
System.out.print("new pass: ");
pass = scan.next();
noWhite = !pass.contains(" ");
oneUppercase = !pass.equals(pass.toLowerCase());
oneDigit = pass.matches(".*\\d.*");
}
System.out.println("OK");

Finding if a specific character exists at a specific index

so I'm trying to figure out how to create a condition for my decision structure. I'm making a program that converts military time to conventional time. When times are entered, they must be in a XX:XX format, where X equals a digit. I'm wondering, how can I make a validation that checks to make sure that ":" always exists as a colon and is in the same spot?
myString.charAt(5) == ':'
Just change 5 to whatever you need, and check string length before you do this, so you don't ask for something past the end of a short string.
You could search the string with indexOf(), which returns the index at which the character is found. This will check if a colon is in the string and if it's in the right position.
if("10:00".indexOf(':') == 2)
// do something
It will return -1 if the value is not found. Check out the java documentation for more information.
Here is the answer for it
Suppose you had string that contains XX:XX
yourString="XX:XX"
yourString.contains(":") - return true - if exists
":" takes the 3rd position. So it will be 2(0,1,2)
yourString.charAt(2) == ':'
Together , it will be
if(yourString.contains(":") && yourString.charAt(2) == ':'){
//your logic here
}else{
something here
}
Here is one approach to that,
String[] test = new String[] { "00:00", "NN:NN", "12,13", "12:13" };
for (String fmt : test) {
boolean isValid = true;
for (int i = 0; i < fmt.length(); i++) {
char c = fmt.charAt(i);
if (i == 2) {
if (c != ':') { // here is the colon check.
isValid = false;
break;
}
} else {
// This checks for digits!
if (!Character.isDigit(c)) {
isValid = false;
break;
}
}
}
System.out.println(fmt + " is " + isValid);
}
Output is
00:00 is true
NN:NN is false
12,13 is false
12:13 is true
#WillBro posted a good answer but I give you another option:
myString.indexOf(":") == 5
With indexOf you can also look for full String inside a String.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
But for string format validations I suggest you to use Regular Expresions.
Here's a full example that does what you want to do:
http://www.mkyong.com/regular-expressions/how-to-validate-time-in-24-hours-format-with-regular-expression/

Categories

Resources