How to regex validate a custom field only if the custom field becomes required?

Luis Tellado July 12, 2021

Thank You in advance! I'm trying to validate the regular expression of a single line custom text field (Incident/s), but only when it becomes required.

Background:

During the Defect create validator, I have a ScriptRunner Behavior on the custom field (Incident/s) to make it required only if the custom field (Found Through) has a value that equals (Production). Then only the custom field (Incident/s) becomes required.

Script:

def field1 = getFieldByName("Incident/s")
def field2 = getFieldByName("Found Through")
def field = getFieldByName("Incident/s")
def val = field.getValue() as String

if(field2.getValue().equals("Production"))
{ field1.setRequired(true) }
else { field1.setRequired(false) }

Goal:

Validate the regex of the single line text field (Incident/s) once it becomes required, to ensure that it begins with "INC" or "RITM" followed by 7 digits.

Help:

def field = getFieldById(getFieldChanged())
def val = field.getValue() as String

if (!val.matches(/(?i)(INC|RITM)[0-9]{7}/)) {
field.setError("Required Format! Must be [INC#######] or [RITM#######]")
} else {
field.clearError()
}

Issue:

I placed this into a second field server-side script within the Behavior. It is working, but how do I handle the blank field value? It is failing the regex validator since its blank. I need it to only regex validate once the field becomes required.

1 answer

1 accepted

2 votes
Answer accepted
Peter-Dave Sheehan
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
July 13, 2021

I think you are very close ... try this in your second field server-side script:

def field = getFieldById(fieldChanged)
def val = field.formValue as String

if (val && !val.matches(/(?i)(INC|RITM)[0-9]{7}/)) {
   field.setError("Required Format! Must be [INC#######] or [RITM#######]")
} else {
   field.clearError()
}

I change how to get the value to use formValue instead of value. I find this more reliable.

And then in the if() we check first if the val exists. if(val) by itself will be true only if val exists and contains some text. If the first condition on the left of && fails, the rest of the condition is not evaluated and it moves the else block.

Luis Tellado July 14, 2021

Thanks Sir Sheehan! Using your approach this did iT!

def field = getFieldById(getFieldChanged())
def val = field.getValue() as String
def regexFormat = /(?i)(INC|RITM)[0-9]{7}/
def regexFormat2 = /(?i).+/

if(!(!val?.trim()) && !(val ==~ regexFormat2)) {
field.setError("Required Format! Must be [INC#######] or [RITM#######]")
} else {
field.clearError()
}

if(!(!val?.trim()) && !(val ==~ regexFormat)) {
field.setError("Required Format! Must be [INC#######] or [RITM#######]")
} else {
field.clearError()
}

Suggest an answer

Log in or Sign up to answer