Simple Script Validators - exact number of digits

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 vote
Tarun Sapra Community Champion Aug 09, 2017

Try this

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

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.

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

Thank you

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 Champion Aug 10, 2017

Just make it

Pattern.compile("^([0-9]{5,8})\$")
Tarun Sapra Community Champion Aug 10, 2017

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

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

0 vote
Tarun Sapra Community Champion Dec 05, 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
How to earn badges on the Atlassian Community

How to earn badges on the Atlassian Community

Badges are a great way to show off community activity, whether you’re a newbie or a Champion.

Learn more
Community showcase
Published Jun 14, 2018 in Jira Service Desk

How the Telegram Integration for Jira helps Sergey's team take their support efficiency to the bank

...+ reading Fantasy). The same is true for him at the bank he works for: Efficiency is key when time literally equals money. Read on to learn how Sergey makes most of the time he has by...

463 views 2 4
Read article

Atlassian User Groups

Connect with like-minded Atlassian users at free events near you!

Find a group

Connect with like-minded Atlassian users at free events near you!

Find my local user group

Unfortunately there are no AUG chapters near you at the moment.

Start an AUG

You're one step closer to meeting fellow Atlassian users at your local meet up. Learn more about AUGs

Groups near you