Validate email field with scriptrunner

Robin Lundberg November 7, 2024

Using Scriptrunner I'm trying to add a custom scripted validator when creating a new issue to check whether or not a customfield contains a valid email address.  

I only want it to validate the email if the Request Type matches X. 

I started with this example script as the base in order to get the Reqest Type name: https://library.adaptavist.com/entity/get-sd-requesttype

This is my script: 

 

import com.atlassian.jira.component.ComponentAccessor

import com.atlassian.servicedesk.api.requesttype.RequestTypeService


import com.onresolve.scriptrunner.runner.customisers.PluginModule

import com.onresolve.scriptrunner.runner.customisers.WithPlugin

import com.atlassian.servicedesk.internal.customfields.origin.VpOrigin

import com.atlassian.servicedesk.internal.feature.customer.request.requesttype.CachedImmutableRequestTypeImpl

@WithPlugin("com.atlassian.servicedesk")

@PluginModule

RequestTypeService requestTypeService



def currentUser = ComponentAccessor.jiraAuthenticationContext.loggedInUser

def customFieldManager = ComponentAccessor.customFieldManager

def requestTypeCustomField = customFieldManager.getCustomFieldObjects(issue).findByName('Customer Request Type')

def requestTypeKey = (issue.getCustomFieldValue(requestTypeCustomField) as VpOrigin)?.requestTypeKey

def query = requestTypeService.newQueryBuilder().issue(issue.id).build()

def requestTypes = requestTypeService.getRequestTypes(currentUser, query).results

def requestType = requestTypes.find { (it as CachedImmutableRequestTypeImpl).key == requestTypeKey }

def requestTypeName = requestType.getName()

if (requestTypeName == "X") {

// Get the value of the custom field

def vendorContactEmail = issue.getCustomFieldValue(16815)

// Validate the email address

if (isValidEmail(vendorContactEmail)) {

return true // Email is valid

} else {

return false // Email is invalid

}

} else {

return true // Request type is not "X", so don't validate the email

}

// Email validation function

boolean isValidEmail(String email) {

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

return email?.matches(emailRegex)

}

The error I keep getting is:

java.lang.NullPointerException: Cannot invoke method getName() on null object

 

I'm not sure why it thinks requestType is a null object. Is it because the ticket hasn't been created yet? 

Thanks for any assistance offered. 

2 answers

0 votes
Bobby Bailey
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
November 8, 2024

Hi @Robin Lundberg , 

I played around with this for a little bit and I suspect I know what the issue is. 

@Tuncay Senturk is correct as to why you are getting the error you are getting, but the root cause is that I suspect you are getting this error when users try to create tickets in Jira itself. 

The problem is that the code here fails:

def requestTypeKey = (issue.getCustomFieldValue(requestTypeCustomField) as VpOrigin)?.requestTypeKey

 

I only took a quick look, but this lines requires the Custom Field "Customer Request Type" to be populated. It looks like with JSM on-prem, the field is populated when the ticket is raised from the portal, but not when manually raised in Jira itself, as you can see here: 

community3.png

So, when you create an issue in Jira itself, you don't have the Customer Request Type, so the script fails to get the value, and then you get the Null pointer. 

 

So, how do we solve it? Well, that depends on your particular needs. As an example, I wrote a little extra code to check to see if we get the Customer Request Type, and if not then I want to use the Issue Type (as in my demo instances they are essentially the same, but with a minor spelling difference, so I just needed to modify the if statement also):

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.servicedesk.api.requesttype.RequestTypeService
import com.onresolve.scriptrunner.runner.customisers.PluginModule
import com.onresolve.scriptrunner.runner.customisers.WithPlugin
import com.atlassian.servicedesk.internal.customfields.origin.VpOrigin
import com.atlassian.servicedesk.internal.feature.customer.request.requesttype.CachedImmutableRequestTypeImpl

@WithPlugin("com.atlassian.servicedesk")
@PluginModule

RequestTypeService requestTypeService

def requestTypeCustomField = customFieldManager.getCustomFieldObjects(issue).findByName('Customer Request Type')
def requestTypeKey = (issue.getCustomFieldValue(requestTypeCustomField) as VpOrigin)?.requestTypeKey

def requestTypeName = ''

if(requestTypeKey){
    def query = requestTypeService.newQueryBuilder().issue(issue.id).build()
    def requestTypes = requestTypeService.getRequestTypes(currentUser, query).results
    def requestType = requestTypes.find { (it as CachedImmutableRequestTypeImpl).key == requestTypeKey }
    requestTypeName = requestType.getName()

} else {
    requestTypeName = issue.getIssueType().getName()
}

if (requestTypeName == "IT help" || requestTypeName == "IT Help") {
    // Get the value of the custom field
    def vendorContactEmail = issue.getCustomFieldValue(10612)

    // Validate the email address
    if (isValidEmail(vendorContactEmail)) {
        return true // Email is valid
    } else {
        return false // Email is invalid
    }

} else {
    return true // Request type is not "X", so don't validate the email
}

// Email validation function
boolean isValidEmail(String email) {
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}\$"

return email?.matches(emailRegex)

}


Let me know if this helps!

Kind regards, 

Bobby

 

Robin Lundberg November 12, 2024

Hi Bobby, 

Thanks for your reply. Unfortunately this doesn't work either. I am creating the ticket through the customer portal, but it seems that the request type still is null. 

I'll see if I can resolve it some other way. 

Best Regards,

Robin

Robin Lundberg November 12, 2024

i had a rethink and came up with a different workaround to my issue. 

import com.atlassian.jira.component.ComponentAccessor

def vendorEmailField = issue.getCustomFieldValue(16815)

// Only validate if the field is not empty
if (vendorEmailField) {
// Regular expression for email validation
def emailRegex = /^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/

if (!(vendorEmailField ==~ emailRegex)) {
// If email format is invalid, return an error
return false
}
}

// If field is empty or validation passes, return true
return true

This way I don't need to check for the request type, it will only do the email validation if the vendorEmailField is present and not empty. 

Best Regards,

Robin

Bobby Bailey
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
November 12, 2024

@Robin Lundberg , 

Interesting! I am not familiar enough with the ins and outs of possibilities with JSM configs, so it might be possible your instance avoids that custom field all together, which would explain why it was never working. 

I am glad you were able to find a workaround! If you need any more help please let me know :-) 

 

Kind regards, 

Bobby

0 votes
Tuncay Senturk
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
November 7, 2024

Hello @Robin Lundberg 

The NullPointerException error is likely occurring because the requestType object is not being set correctly, which could be due to the fact that the issue is not fully created 'as you mentioned', and the Request Type field might not yet have the necessary data to return a valid object.

the requestTypeCustomField might not yet contain a value. You need to check if the field is null before proceeding.

if (!requestTypeCustomField) { 
   return true // Skip validation if the Request Type field is not found
}

and also requestTypeKey

// Ensure that requestTypeKey is not null 
if (!requestTypeKey) {
return true // Skip validation if requestTypeKey is not available
}

and

// Ensure that requestType is not null before accessing its name 
if (requestType == null) {
return true // Skip validation if requestType is null
}

 

 

Robin Lundberg November 12, 2024

Hi Tuncay, 

Thanks for your reply, I actually tried checking if the request type is null before posting. The problem then is that it will always bypass the email validation. Even when I submit the ticket through the specific request type form from the servicedesk portal.


Best Regards,

Robin

Suggest an answer

Log in or Sign up to answer