Search code examples
javastringvalidationstring-formattingstring-comparison

String validation based on criteria


I have a requirement where I need to validate a string:

   String input1 = example@gmail.com , example1@gmail.com; 
   String input2 = example@yahoo.com , example1@gmail.com;

        String input 1 == valid ::: Valid because all email ids are of same domain

       String input 2 == invalid

Solution

  • You can build the logic in the following way. String input1 = example@gmail.com , example1@gmail.com , example1@gmail.com;

    Follow the steps.

    1. Split the entire string using comma (,). You will get an array of email ids.
    2. From the above array of email id, separate out the domain by stripping from @ symbol and put in a HashSet. It means the HashSet should contain all the domains.
    3. If the HashSet size is 1 finally or at the end it means that input1 has same doamins, as per your requirement it is valid.
    4. If the HashSet contains more than 1, as per your requirement it is invalid.

    This is a simple logic, However there may be better logic to solve it.