Validation – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Mon, 18 Oct 2021 12:26:39 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Validation – Java2Blog https://java2blog.com 32 32 Input validation in java using Scanner https://java2blog.com/input-validation-java/?utm_source=rss&utm_medium=rss&utm_campaign=input-validation-java https://java2blog.com/input-validation-java/#respond Mon, 28 Sep 2020 19:01:14 +0000 https://java2blog.com/?p=10708 In this post, we will see how to do input validation in java using Scanner class.

The Java Scanner class is used to get input from user. It provides several methods to get input of different types and to validate the input as well. Here we will see some of these methods that can be used to get user input and do the input validation in java.

Scanner Methods to Validate User Input

MethodDescription
boolean hasNext​(String pattern)It returns true if the next token matches the pattern constructed from the specified string.
boolean hasNext​(Pattern pattern)It returns true if the next complete token matches the specified pattern.
boolean hasNextBigDecimal​()It returns true if the next token in this scanner's input can be interpreted as a BigDecimal using the nextBigDecimal() method.
boolean hasNextBigInteger​()It returns true if the next token in this scanner's input can be interpreted as a BigInteger in the default radix using the nextBigInteger() method.
boolean hasNextBigInteger​(int radix)It returns true if the next token in this scanner's input can be interpreted as a BigInteger in the specified radix using the nextBigInteger() method.
boolean hasNextBoolean​()It returns true if the next token in this scanner's input can be interpreted as a boolean value using a case insensitive pattern created from the string "true|false".
boolean hasNextByte​()It returns true if the next token in this scanner's input can be interpreted as a byte value in the default radix using the nextByte() method.
boolean hasNextByte​(int radix)It returns true if the next token in this scanner's input can be interpreted as a byte value in the specified radix using the nextByte() method.
boolean hasNextDouble​()It returns true if the next token in this scanner's input can be interpreted as a double value using the nextDouble() method.
boolean hasNextFloat​()It returns true if the next token in this scanner's input can be interpreted as a float value using the nextFloat() method.
boolean hasNextInt​()It returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method.
boolean hasNextInt​(int radix)It returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using the nextInt() method.
boolean hasNextLine​()It returns true if there is another line in the input of this scanner.
boolean hasNextLong​()It returns true if the next token in this scanner's input can be interpreted as a long value in the default radix using the nextLong() method.
boolean hasNextLong​(int radix)It returns true if the next token in this scanner's input can be interpreted as a long value in the specified radix using the nextLong() method.
boolean hasNextShort​()It returns true if the next token in this scanner's input can be interpreted as a short value in the default radix using the nextShort() method.
boolean hasNextShort​(int radix)It returns true if the next token in this scanner's input can be interpreted as a short value in the specified radix using the nextShort() method.

Scanner Methods to get User Input

MethodDescription
String next​(String pattern)It returns the next token if it matches the pattern constructed from the specified string.
String next​(Pattern pattern)It returns the next token if it matches the specified pattern.
BigDecimal nextBigDecimal​()It scans the next token of the input as a BigDecimal.
BigInteger nextBigInteger​()It scans the next token of the input as a BigInteger.
BigInteger nextBigInteger​(int radix)It scans the next token of the input as a BigInteger.
boolean nextBoolean​()It scans the next token of the input into a boolean value and returns that value.
byte nextByte​()It scans the next token of the input as a byte.
byte nextByte​(int radix)It scans the next token of the input as a byte.
double nextDouble​()It scans the next token of the input as a double.
float nextFloat​()It scans the next token of the input as a float.
int nextInt​()It scans the next token of the input as an int.
int nextInt​(int radix)It scans the next token of the input as an int.
String nextLine​()it advances this scanner past the current line and returns the input that was skipped.
long nextLong​()It scans the next token of the input as a long.
long nextLong​(int radix)It scans the next token of the input as a long.
short nextShort​()It scans the next token of the input as a short.
short nextShort​(int radix)It scans the next token of the input as a short.

Input validation using Scanner class

We can do different type of input validation using different hasNextXXX() methods.

Validate integer input using Scanner in Java

We can use hasNextInt() method to check whether the input is integer and then get that using nextInt() method. See the example below.

import java.util.Scanner;
public class Main
{
    public static void main(String args[]) 
    {
        int input = 0;
        System.out.println("Enter an Integer value ");
        Scanner sc = new Scanner(System.in);
        if(sc.hasNextInt()) {
            input = sc.nextInt();
            if(input>0)
                System.out.println("You entered a positive integer "+input);
            else {
                System.out.println("You entered a negative integer "+input);
            }
        }else {
            System.out.println("Please Enter Valid Integer");
        }
    }
}

Output

Enter an Integer value
50
You entered a positive integer 50

Validate Floating point input using Scanner in Java

To validate floating-point values, we used hasNextDouble() method that returns true if the input is floating type and nextDouble() method is used to get the user input.

import java.util.Scanner;
public class Main
{
    static Double input;
    public static void main(String args[]) 
    {
        System.out.println("Enter a floating point value ");
        Scanner sc = new Scanner(System.in);
        if(sc.hasNextDouble()) {
            input = sc.nextDouble();
            if(input>0)
                System.out.println("You entered a positive value "+input);
            else {
                System.out.println("You entered a negative value "+input);
            }
        }else {
            System.out.println("Please Enter a Valid Value");
        }
    }
}

Output:

Enter a floating point value
25.21
You entered a positive value 25.21

Validate Boolean input using Scanner in Java

We can use hasNextBoolean() method to check whether the input is a valid boolean or not and nextBoolean() method is used to get the input value.

import java.util.Scanner;
public class Main
{
    static Boolean input;
    public static void main(String args[]) 
    {
        System.out.println("Enter a boolean value ");
        Scanner sc = new Scanner(System.in);
        if(sc.hasNextBoolean()) {
            input = sc.nextBoolean();
            System.out.println("You entered a boolean value "+input);
        }else {
            System.out.println("Please Enter a Valid Value");
        }
    }
}

Output

Enter a boolean value
false
You entered a boolean value false

Validate String input using Scanner in Java

To validate a string value, we can use regex to get string in a specific format. Here, the hasNext() takes a regex to validate a string that can contain only alphabets. See the example below.

import java.util.Scanner;
public class Main
{
    static String input;
    public static void main(String args[]) 
    {
        System.out.println("Enter a String ");
        Scanner sc = new Scanner(System.in);
        if(sc.hasNext("[A-Za-z]*")) {
            input = sc.next();
            System.out.println("You entered a string value "+input);
        }else {
            System.out.println("Please Enter a Valid Value");
        }
    }
}

Output

Enter a String
java
You entered a string value java

That’s all about Input validation in java using Scanner.

]]>
https://java2blog.com/input-validation-java/feed/ 0
Validate password in java https://java2blog.com/validate-password-java/?utm_source=rss&utm_medium=rss&utm_campaign=validate-password-java https://java2blog.com/validate-password-java/#comments Mon, 04 May 2020 13:32:53 +0000 https://java2blog.com/?p=9711 In this post, we will see how to validate a password in java.
Here are rules for password:

  1. Must have at least one numeric character
  2. Must have at least one lowercase character
  3. Must have at least one uppercase character
  4. Must have at least one special symbol among @#$%
  5. Password length should be between 8 and 20

Using regex

Here is standard regex for validating password.

^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20}$

Here is explanation for above regex

^ asserts position at start of a line
Group (?=.*\\d)
Assert that the Regex below matches
.* matches any character (except for line terminators)
\\ matches the character \ literally (case sensitive)
d matches the character d literally (case sensitive)
Group (?=.*[a-z])
Assert that the Regex below matches
.* matches any character (except for line terminators)
Match a single character present in the list below [a-z]
a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)
Group (?=.*[A-Z])
Assert that the Regex below matches
.* matches any character (except for line terminators)
Match a single character present in the list below [A-Z]
A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)
Group (?=.*[@#$%])
Assert that the Regex below matches
.* matches any character (except for line terminators)
Match a single character present in the list below [@#$%]
@#$% matches a single character in the list @#$% (case sensitive)
.{8,20} matches any character (except for line terminators)
{8,20} Quantifier — Matches between 8 and 20 times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of a line

Here is java program to implement it.

package org.arpit.java2blog;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexCurrencySymbol {

    public static void main(String args[]) {
        String password1 = "Java2blog@";

        String regex = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20}$";
        boolean validPassword = isValidPassword(password1,regex);
        System.out.println("Java2blog@ is valid password:" +validPassword);

        String password2 = "helloword#123";

        String regex1 = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20}$";
        boolean validPassword1 = isValidPassword(password2,regex1);
        // No upper case
        System.out.println("helloword#123 is valid password:" +validPassword1);
    }

    public static boolean isValidPassword(String password,String regex)
    {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(password);
        return matcher.matches();
    }
}

Output:

Java2blog@ is valid password:true
helloword#123 is valid password:false

Using String’s matches method

We can also use string’s matches() method to validate password in java.
Let’s see with the help of an example.

package org.arpit.java2blog;

public class PasswordValidatorMain {

    public static void main(String args[]) {
        String password1 = "Java2blog@";

        boolean validPassword = isValidPassword(password1);
        System.out.println("Java2blog@ is valid password:" +validPassword);

        String password2 = "helloword#123";

        boolean validPassword1 = isValidPassword(password2);
        // No upper case
        System.out.println("helloword#123 is valid password:" +validPassword1);
    }

    /**
     * Method to check if password is valid or not.
     * @param password
     * @return boolean
     */
    public static boolean isValidPassword(String password)
    {
            boolean isValid = true;
            if (password.length() > 15 || password.length() < 8)
            {
                    System.out.println("Password must be less than 20 and more than 8 characters in length.");
                    isValid = false;
            }
            String upperCaseChars = "(.*[A-Z].*)";
            if (!password.matches(upperCaseChars ))
            {
                    System.out.println("Password must have atleast one uppercase character");
                    isValid = false;
            }
            String lowerCaseChars = "(.*[a-z].*)";
            if (!password.matches(lowerCaseChars ))
            {
                    System.out.println("Password must have atleast one lowercase character");
                    isValid = false;
            }
            String numbers = "(.*[0-9].*)";
            if (!password.matches(numbers ))
            {
                    System.out.println("Password must have atleast one number");
                    isValid = false;
            }
            String specialChars = "(.*[@,#,$,%].*$)";
            if (!password.matches(specialChars ))
            {
                    System.out.println("Password must have atleast one special character among @#$%");
                    isValid = false;
            }
            return isValid; 
    }
}

Output:

Java2blog@ is valid password:true
Password must have atleast one uppercase character
helloword#123 is valid password:false

That’s all about how to validate password in java.

]]>
https://java2blog.com/validate-password-java/feed/ 1
Java regex for currency symbols https://java2blog.com/java-regex-for-currency-symbols/?utm_source=rss&utm_medium=rss&utm_campaign=java-regex-for-currency-symbols https://java2blog.com/java-regex-for-currency-symbols/#respond Mon, 04 May 2020 13:31:46 +0000 https://java2blog.com/?p=9707 In this post, we will see about regex to find currency symbols in a text.

You can use below regex to find currency symbols in any text.

\\p{Sc}

Each unicharacter belongs to certain category and you can search for it using /p. Sc is short code for current symbol, so using \p{Sc}, we are trying to find currency symbol in a text.

package org.arpit.java2blog;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexCurrencySymbol {

    public static void main(String args[]) {
        String text = "Currency symobols are : $ Dollar, ₹ Rupees ";

        String regex = "\\p{Sc}";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            System.out.print("Start index: " + matcher.start());
            System.out.print(" End index: " + matcher.end() + " ");
            System.out.println(" : " + matcher.group());
        }
    }
}

Output:

Start index: 24 End index: 25 : $
Start index: 34 End index: 35 : ₹

That’s all about regex for currency symbols in java.

]]>
https://java2blog.com/java-regex-for-currency-symbols/feed/ 0
Java credit card validation – Luhn Algorithm in java https://java2blog.com/luhn-algorithm-java/?utm_source=rss&utm_medium=rss&utm_campaign=luhn-algorithm-java https://java2blog.com/luhn-algorithm-java/#respond Mon, 04 May 2020 13:27:40 +0000 https://java2blog.com/?p=9580 In this post, we will see about Luhn Algorithm in java

Introduction

Luhn algorithm, also known as modulus 10 or mod 10 algorithm, is a simple checksum process for validating various identification numbers such as credit card numbers, Canadian social securities numbers.
This algorithm is designed to protect again mistyped or accidental error rather than malicious attacks. Most credit card companies adopted this algorithm as this was available in the public domain and can be used by anyone.

Here are the steps involved in Luhn Algorithms.


Step 1:
From the rightmost digit, we should double every second digit.

LuhnAlgorithmMulBy2


Step 2:
When we double the digits and get product in double digits, then we should add digits of the product.

LuhnAlgorithmSumDigits


Step 3:
Compute the sum of all the digits.


Step 4:
If total sum is divisible by 10 i.e. total sum modulo 10 is 0, then number is valid else it is not valid.

LuhnAlgorithmCheckValid

As 90 mod 10 is 0, hence this is valid credit card number.

Detailed implementation

Let’s create java program to implement the Luhn algorithm.

package org.arpit.java2blog;

import java.util.Arrays;

public class LuhnAlgorithmMain {

    public static void main(String[] args) {

        String cardNumber="1358954993914435";

        boolean validCreditCardNumber = isValidCreditCardNumber(cardNumber);

        if(validCreditCardNumber)
        {
            System.out.println(cardNumber+" is valid as per luhn algorithm");
        }
        else
        {
            System.out.println(cardNumber+" is not valid as per luhn algorithm");
        }
    }

    public static boolean isValidCreditCardNumber(String cardNumber)
    {
        // int array for processing the cardNumber
        int[] cardIntArray=new int[cardNumber.length()];

        for(int i=0;i=0;i=i-2)
        {
            int num = cardIntArray[i];
            num = num * 2;  // step 1
            if(num>9)
            {
                num = num%10 + num/10;  // step 2
            }
            cardIntArray[i]=num;
        }

        int sum = sumDigits(cardIntArray);  // step 3

        System.out.println(sum);

        if(sum%10==0)  // step 4
        {
            return true;
        }

        return false;

    }

    public static int sumDigits(int[] arr)
    {
        return Arrays.stream(arr).sum();
    }
}

Output:

90
1358954993914435 is valid as per luhn algorithm

Here are the steps involved in above java program for luhn algorithm.

  1. Convert a String cardNumber to int array cardIntArray for processing
  2. Iterate cardIntArray from rightmost side starting from cardIntArray.length-2 with step of i=i-2
  3. Mulitply digit by 2
  4. If product is greater than 9, sum the product
  5. Assign result back to cardIntArray[i]
  6. Once the loop is over, compute sum of elements of cardIntArray
  7. if sum%10 is 0 then credit card number is valid else not valid as per luhn algorithm

Using Apache common validation

In case, you don’t want to implement luhn algorithm you can use Apache common validation library and validate credit card number using LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(creditCardNumber);

You need to add following dependency to pom.xml.

<!-- https://mvnrepository.com/artifact/commons-validator/commons-validator -->
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.6</version>
</dependency>

Let’s see with the help of example:

package org.arpit.java2blog;

import org.apache.commons.validator.routines.checkdigit.LuhnCheckDigit;

public class LuhnAlgorithmApache {

    public static void main(String[] args) {

        String cardNumber="79927398713";

        boolean validCreditCardNumber = isValidCreditCardNumberLuhn(cardNumber); 

        if(validCreditCardNumber)
        {
            System.out.println(cardNumber+" is valid as per luhn algorithm");
        }
        else
        {
            System.out.println(cardNumber+" is not valid as per luhn algorithm");
        }
    }

    public static boolean isValidCreditCardNumberLuhn(String creditCardNumber)
    {
        return LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(creditCardNumber);
    }
}

Output:

79927398713 is valid as per luhn algorithm

That’s all about Luhn Algorithm in java

]]>
https://java2blog.com/luhn-algorithm-java/feed/ 0
Java isNull method https://java2blog.com/java-isnull/?utm_source=rss&utm_medium=rss&utm_campaign=java-isnull https://java2blog.com/java-isnull/#respond Sat, 21 Mar 2020 14:29:59 +0000 https://java2blog.com/?p=8915 In this post, we will about Objects class’s isNull method.

Objects’s isNull() method is used to check if object is null or not. java.util.Objects class was introduced in java 7.

Here is simple example for Object's isNull method.

package org.arpit.java2blog;

import java.util.Objects;

public class ObjectsIsNullMain {

    public static void main(String[] args) {
        String str1="Java2blog";
        String str2=null;

        System.out.println("Is str1 null: "+Objects.isNull(str1));
        System.out.println("Is str2 null: "+Objects.isNull(str2));
    }
}

Output:

Is str1 null: false
Is str2 null: true

Let’s look at source code Object’s isNull() method.

/**
     * Returns {@code true} if the provided reference is {@code null} otherwise
     * returns {@code false}.
     *
     * @apiNote This method exists to be used as a
     * {@link java.util.function.Predicate}, {@code filter(Objects::isNull)}
     *
     * @param obj a reference to be checked against {@code null}
     * @return {@code true} if the provided reference is {@code null} otherwise
     * {@code false}
     *
     * @see java.util.function.Predicate
     * @since 1.8
     */
    public static boolean isNull(Object obj) {
        return obj == null;
    }

As you can see, it just checks if obj is null or not.

Advantage of isNull over obj==null

  1. In case, you are checking if boolean variable is null or not. You can make typo as below.

    Boolean boolVar=true;     
        if(boolVar = null)  // typo
        {
    
        }

    You can use isNull() method to avoid this kind of typos.

    Boolean boolVar=true;     
        if(Objects.isNull(boolVar))  // typo
        {
    
        }
  2. Object’s isNull() method can be used with Java 8 lambda expressions.

It is cleaner and easier to write.

.stream().filter(Objects::isNull)

than to write:

.stream().filter(a -> a == null).

That’s all about isNull method in java.

]]>
https://java2blog.com/java-isnull/feed/ 0
Validate phone number in java https://java2blog.com/validate-phone-number-java/?utm_source=rss&utm_medium=rss&utm_campaign=validate-phone-number-java https://java2blog.com/validate-phone-number-java/#respond Thu, 25 Jul 2019 17:43:24 +0000 https://java2blog.com/?p=7677 In this post, we will see how to validate phone number in java.


Validate any international phone number as per E.123

E.123 is a standards-based recommendation by the International Telecommunications Union sector ITU-T.

E.123 provides following specifications.

  • The leading plus (+) serves as an international prefix symbol, and is immediately followed by the country code and then phone number.
  • Spaces should separate country code, area code and local number.

Regex

^\+(?:[0-9] ?){6,14}[0-9]$

Explanation

^ –> Assert position at the beginning of the string.
\+ –> Match a literal “+” character.
(?: –> Group but don’t capture:
[0-9] –> Match a digit from 0-9.
\x20 –> Match a space character(used x20 to show space character)
? –> between zero and one time.
) –> End the noncapturing group.
{6,14} –> Recur the group between 6 and 14 times.
[0-9] –> Match digit from 0-9
$ –> Assert position at the end of the string.

Java program to check phone number

package org.arpit.java2blog;

// Java program to check phone 
// is valid as per E123 
import java.util.regex.Matcher;
import java.util.regex.Pattern; 

public class ValidatePhoneNumberMain { 
    public static boolean isValidE123(String s) 
    { 
        Pattern p = Pattern.compile("^\\+(?:[0-9] ?){6,14}[0-9]$"); 

        Matcher m = p.matcher(s); 
        return (m.find() && m.group().equals(s)); 
    } 

    public static void main(String[] args) 
    { 
        String phone1 = "+91 3423 546443"; 
        String phone2 = "+44 343 2324";
        String phone3 = "91 4354 3454";
        String[] phoneNumbers= {phone1,phone2,phone3};

        for (int i = 0; i < phoneNumbers.length; i++) {
            String phoneNumber=phoneNumbers[i];
            if (isValidE123(phoneNumber)) 
                System.out.print(phoneNumber+" is valid phone number"); 
            else
                System.out.print(phoneNumber+" is invalid Phone number"); 

            System.out.println();
        }    
    } 
}

Output

+91 3423 546443 is valid phone number
+44 343 2324 is valid phone number
91 4354 3454 is invalid Phone number

Validate Indian mobile number

Valid indian mobile numbers are:

9876543210
09876543210
919876543210
0919876543210
+919876543210
+91-9876543210
0091-9876543210
+91 -9876543210
+91- 9876543210
+91 – 9876543210
0091 – 9876543210

Regex

^(?:(?:\\+|0{0,2})91(\\s*[\\-]\\s*)?|[0]?)?[789]\\d{9}$

Explanation

I would recommend to go to site https://regex101.com/. Put the regex in regular expression. It will show you clear explanation of regex.
Here is java program for the validate indian mobile number

package org.arpit.java2blog;

// Java program to check phone 
// is valid as per E123 
import java.util.regex.Matcher;
import java.util.regex.Pattern; 

public class ValidatePhoneNumberMain { 
    public static boolean isValidIndianMobileNumber(String s) 
    { 
        Pattern p = Pattern.compile("^(?:(?:\\+|0{0,2})91(\\s*[\\-]\\s*)?|[0]?)?[789]\\d{9}$"); 

        Matcher m = p.matcher(s); 
        return (m.find() && m.group().equals(s)); 
    } 

    public static void main(String[] args) 
    { 
        String phone1 = "+91-7123456789"; 
        String phone2 = "08123456789";
        String phone3 = "9876543210";
        String[] phoneNumbers= {phone1,phone2,phone3};

        for (int i = 0; i < phoneNumbers.length; i++) {
            String phoneNumber=phoneNumbers[i];
            if (isValidIndianMobileNumber(phoneNumber)) 
                System.out.print(phoneNumber+" is valid mobile number"); 
            else
                System.out.print(phoneNumber+" is invalid mobile number"); 

            System.out.println();
        }    
    } 
}

Output

+91-7123456789 is valid mobile number
08123456789 is valid mobile number
9876543210 is valid mobile number

That’s all about validate phone number in java.

]]>
https://java2blog.com/validate-phone-number-java/feed/ 0
Validate email address in java https://java2blog.com/validate-email-address-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=validate-email-address-in-java https://java2blog.com/validate-email-address-in-java/#respond Thu, 11 Jul 2019 17:12:40 +0000 https://java2blog.com/?p=7670 In this post, we will see how to validate email address in java.

There are times when you have to validate email address provided by user. You might want to write your own logic to validate email addresses but there are lots of standard regular expressions or libraries which can help you validate email address and provide great results.

Email address is made up of local part, @ and followed by domains. You can go through wiki page for format of email address.


Using regular expressions

We can use regular expression provided by OWASP Validation Regex Repository which is considered to be safe and will solve the purpose in most of the cases.

Here is the regular expression

^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$

Here is complete java program for email address validation in java

package org.arpit.java2blog;

import java.util.regex.Pattern; 

public class EmailValidatorMain 
{ 
    public static boolean isValid(String email) 
    { 
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@" +  //part before @
                "(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$"; 

        Pattern pat = Pattern.compile(emailRegex); 
        if (email == null) 
            return false; 
        return pat.matcher(email).matches(); 
    } 

    /* driver function to check */
    public static void main(String[] args) 
    { 
        String email1 = "[email protected]"; 
        String email2 = "@java2blog.com";
        String email3 = "[email protected]";
        String[] emails= {email1,email2,email3};

        for (int i = 0; i < emails.length; i++) {
            String email=emails[i];
            if (isValid(email)) 
                System.out.print(email+" is valid email"); 
            else
                System.out.print(email+" is invalid email"); 

            System.out.println();
        }
    } 
}

When you run above program, you will get below output

[email protected] is valid email
@java2blog.com is invalid email
[email protected] is valid email

Using apache common validator library

You can also use inbuilt apache librabry to validate the address. If you are using maven, then you need to add below dependency in your pom.xml.

<!-- https://mvnrepository.com/artifact/commons-validator/commons-validator -->
<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.4.0</version>
</dependency>

Here is java program for the same.

package org.arpit.java2blog;

import org.apache.commons.validator.routines.EmailValidator;

public class EmailValidatorMain 
{ 
    public static boolean isValid(String email) 
    { 
        // Get an EmailValidator instance first
        EmailValidator validator = EmailValidator.getInstance();

        // check valid email address
        if (!validator.isValid(email)) {
            return false;
        }
        return true;
    } 

    /* driver function to check */
    public static void main(String[] args) 
    { 
        String email1 = "[email protected]"; 
        String email2 = "@java2blog.com";
        String email3 = "[email protected]";
        String[] emails= {email1,email2,email3};

        for (int i = 0; i < emails.length; i++) {
            String email=emails[i];
            if (isValid(email)) 
                System.out.print(email+" is valid email"); 
            else
                System.out.print(email+" is invalid email"); 

            System.out.println();
        }
    } 
}

When you run above program, you will get below output

[email protected] is valid email
@java2blog.com is invalid email
[email protected] is valid email

That’s all about validate email address in java.

]]>
https://java2blog.com/validate-email-address-in-java/feed/ 0
Java Regex for alphanumeric characters https://java2blog.com/java-regex-alphanumeric/?utm_source=rss&utm_medium=rss&utm_campaign=java-regex-alphanumeric https://java2blog.com/java-regex-alphanumeric/#respond Fri, 08 Jun 2018 09:40:55 +0000 https://java2blog.com/?p=5690 In this post, we will see how to create regex alphanumeric which will create only alphanumeric characters.
There are times when you need to validate the user’s input. It should contain only characters from a-z, A-Zor 0-9.
Here is simple regex for it.

^[a-zA-Z0-9]*$

Here is the explaination of above regex.

^ : start of string
[ : beginning of character group
a-z : any lowercase letter
A-Z : any uppercase letter
0-9 : any digit
_ : underscore
]: end of character group
* : zero or more of the given characters
$ : end of string

If you do not want to allow empty string, you can use + instead of *.

^[a-zA-Z0-9]+$
Java program to test regex alphanumeric characters.

package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExample {

    public static void main(String args[])
    {
        List<String> listOfUserNames=new ArrayList<>();
        listOfUserNames.add("Java2blog");
        listOfUserNames.add("Java-2-blog");
        listOfUserNames.add("Java2blog Tutorials");
        listOfUserNames.add("Java2blogTutorials");
        listOfUserNames.add("");

        String regex = "^[a-zA-Z0-9]*$";

        Pattern pattern = Pattern.compile(regex);

        for (String name : listOfUserNames)
        {
          Matcher matcher = pattern.matcher(name);
          System.out.println("Only Alphanumeric in "+name+" : "+ matcher.matches());
        }
    }
}

Output

Only Alphanumeric in Java2blog : true
Only Alphanumeric in Java-2-blog : false
Only Alphanumeric in Java2blog Tutorials : false
Only Alphanumeric in Java2blogTutorials : true
Only Alphanumeric in : true

That’s all about Java Regex – alphanumeric characters

]]>
https://java2blog.com/java-regex-alphanumeric/feed/ 0