Forum Discussion

chathurad's avatar
chathurad
Contributor
6 years ago
Solved

How to validate a email address from groovy scripting

import net.sf.json.groovy.*;
import net.sf.json.groovy.JsonSlurper;

def Res = context.expand( '${Users - Request 1#Response}' )

def slurper = new JsonSlurper()

def json = slurper.parseText Res
def Email = json.email

From the above code I got an array of emails from my response data set.

Now i want to check that all the emails has a "@" sign. and at least one "." .

How can i do this.

 

For now at least "@" verification is enough 

  • I did by below code.

     

    import net.sf.json.groovy.*;
    import net.sf.json.groovy.JsonSlurper;
    
    def Res = context.expand( '${Users - Request 1#Response}' )
    
    def slurper = new JsonSlurper()
    
    def json = slurper.parseText Res
    def Email = json.email
    
    int i =0;
    
    Email.each()
    {
    	assert Email[i].contains('@')
    	
    	log.info Email[i]
    	i++
    }

2 Replies

  • I did by below code.

     

    import net.sf.json.groovy.*;
    import net.sf.json.groovy.JsonSlurper;
    
    def Res = context.expand( '${Users - Request 1#Response}' )
    
    def slurper = new JsonSlurper()
    
    def json = slurper.parseText Res
    def Email = json.email
    
    int i =0;
    
    Email.each()
    {
    	assert Email[i].contains('@')
    	
    	log.info Email[i]
    	i++
    }
  • richie's avatar
    richie
    Community Hero

    Hey,

     

    I would've thought you can use jsonpath regex match assertion if you want to use the OTB functionality - you just need to determine the regex for your email address - email addresses are a littel awkward with regex - there's lots of different options trying to cover all permutations.

     

    Found via link

     

    Here's one --> ^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$

     

    And this covers the following:  Doesn't allow numbers in the domain name and doesn't allow for top level domains that are less than 2 or more than 3 letters (which is fine until they allow more). Doesn't handle multiple "." in the domain (joe@abc.co.uk).  If the 'allowed' email addresses are different - tailor the above regex accordingly

     

    If you just need literally something to verify that the @ is in the email address and that the email address is comprised of up to 255 chars you could try the following regex (which I've just put together now) [a-z][A-Z][0-9]{250}@.[a-z][A-Z]{3} - this is a lot more basic than the above regex from the link - but it might do the job.

     

    I suppose as you're using a script, you might want to add the assertion into your script - with this in mind, please see the following stackoverflow link which has details on asserting regex values

     

    I'm not a scripter - so I can't give you the code - but hopefully the details/links above might help get you there

     

    hope the above helps,

     

    richie