Home > Software engineering >  Allow only numbers, periods and commas in a TextField
Allow only numbers, periods and commas in a TextField

Time:12-31

The following code effectively limits a TextFild to only numbers, periods . and commas , which is what I want. The issue is that it allows the user to enter a period . and a comma , if a period is entered first.

How can I modify the Regex expression below to prevent the user from entering a comma , if a period . already exists, and vice-versa?

struct TextFieldNumbersOnly: View {
    @State private var inputValue = ""

    var body: some View {
        TextField("enter numbers", text: self.$inputValue)
            //.keyboardType(.decimalPad) //commented out for testing purposes only
            .onReceive(Just(self.inputValue), perform: self.textInputValidator)
    }
    
    func textInputValidator(newValue: String) {
        if newValue.range(of: "^[\\d]*(?:\\.?\\,?[\\d]*)?$", options: .regularExpression) != nil {
            self.inputValue = newValue
        } else if !self.inputValue.isEmpty {
            self.inputValue = String(newValue.prefix(self.inputValue.count - 1))
        }
    }
}

FYI - If I type a comma before a period, it doesn't let me enter the period, which is what I want, it just doesn't do it the other way around.

CodePudding user response:

Try this:

^\d [.,]?\d*$|^[.,]\d*$

^\d [.,]?\d*$

  • ^ match the start of the string/line.
  • \d match one or more digit.
  • [.,]? match an optional literal . or ,.
  • \d* match zero or more digits.
  • $ match the end of the string/line.

| the alternation operator it is like Boolean OR

^[.,]\d*$

  • ^ match the start of the string/line.
  • [,.] match one literal . or ,.
  • \d* match zero or more digits.
  • $ match the end of the string/line.

See regex demo

  • Related