Simple Script Validators - exact number of digits

Anna Protopapa August 9, 2017

Hello,

I want to have a validation for an optional field that has exactly 8 digits.

My code is:

 // Import Regex

import java.util.regex.*;

// Construct The Pattern to Match on

Pattern pattern = Pattern.compile("([0-9]){8}");

// Check if the PhoneNumber Field is a match

cfValues['PhoneNumber'] == null || pattern.matcher(issue.getCustomFieldValue(customFieldManager.getCustomFieldObjectByName("PhoneNumber")).toString())  

 

The problem is that allows can insert more than 8 digits.

2 answers

1 accepted

0 votes
Answer accepted
Tarun Sapra
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
August 9, 2017

Try this

Pattern.compile("^([0-9]{8})$")
Tarun Sapra
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
August 9, 2017

Anna you were missing the dollar sign ($) in your snippet which means "don't add anything after me" as dollar sign means end of line.

Anna Protopapa August 9, 2017

It works with Pattern.compile("^([0-9]{8})\$")

Thank you

Anna Protopapa August 10, 2017

I want to ask another case: If I need the number of digits to be between 5 to 8 digits, how I will write the command?

Tarun Sapra
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
August 10, 2017

Just make it

Pattern.compile("^([0-9]{5,8})\$")
Tarun Sapra
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
August 10, 2017

If it works for you, please accept the answer. thanks.

Anna Protopapa August 10, 2017

Thank you!!

Stefani Kaimakliotou December 5, 2017

What if we want to add special characters like "-" to the above snippet? e.g 9956-56

0 votes
Tarun Sapra
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
December 5, 2017

Hi @Stefani Kaimakliotou

Your requirement of "9956-56" can be implemented with the snippet

Pattern.compile("^([-0-9]{5,8})\$")

i.e. digits with "-" (dash) and total length of 5 to 8 

Suggest an answer

Log in or Sign up to answer