Search code examples
swift3

Regular Expression to validate Rate of Interest Format Swift3


I have been trying to work on Regular Expressions for one of my TextField to only allow digits in Rate of Interest format.

I want the field to allow input of max 2 digits before "." character and max 2 digits after.

Valid Formats:

1, 10, 1.2, 11.4, 15.24

And Max length of the field to be 5 characters

I tried a few but nothing worked out.


Solution

  • Try the below code

    let string = "10.55"
    
    if let match = string.range(of: "^\\d{1,2}(\\.\\d{1,2})?$", options: .regularExpression) {
        print("Match")
    }
    

    Or you can use guard too

    guard let match = string.range(of: "^\\d{1,2}(\\.\\d{1,2})?$", options: .regularExpression) else {
        return
    }