0

I have been trying to write a function that validates if a given Double is a number between 1-100. And only whole numbers, so something like 1.5 would not be allowed. Allowed would be 1,2,3,...,100. I'm using the following regex for that ->

"^([1-9][0-9]?$)|^100$" 

however, even if i input 100, my function never gives me back true. In which way is my regex wrong?

this is the rest of my code

func validate(input: Double) -> Bool {

        let regex = "^([1-9][0-9]?$)|^100$"

        let inputTest = NSPredicate(format: "SELF MATCHES %@", regex)
        return inputTest.evaluate(with: String(input)) 
}

the input has to be a Double.

Misha
  • 181
  • 11

1 Answers1

0

You don't need a regex or a predicate. Simply do some basic checking as follows:

func validate(input: Double) -> Bool {
    return input >= 1 && input <= 100 && round(input) == input;
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579