I am trying to incorporate a custom ORKTextAnswerFormat
into my app, and only allow users to enter alphanumeric characters. I only want upper/lowercase letters and numbers - no symbols or accented letters.
E.G. they should not be allowed to enter "example!", as it includes an exclamation mark.
The code I have tried so far is as follows:
// REGEX
let linkRegexPattern = "[^a-zA-Z0-9]"
let linkRegex = try! NSRegularExpression(pattern: linkRegexPattern,
options: .caseInsensitive)
// CUSTOM STEP TO INPUT PATIENT ID
let patientidTitle = "Patient ID"
let patientidQuestion = "Enter the Patient ID provided to you by the hospital."
let patientidAnswerFormat = ORKTextAnswerFormat(validationRegularExpression: linkRegex, invalidMessage: "INVALID")
patientidAnswerFormat.maximumLength = 20
patientidAnswerFormat.multipleLines = false
let patientidStep = ORKQuestionStep(identifier: "patientIDstep", title: patientidTitle, question: patientidQuestion, answer: patientidAnswerFormat)
patientidStep.isOptional = false
However upon entering the above example, I am able to press next and move on to the next question/step with no errors thrown. I would like it to not allow me to proceed until the input is suitable.
How can I achieve this?
EDIT:
If I input "test" it alerts saying it is invalid. However, inputting "test!" allows me to continue.
The [^a-zA-Z0-9]
pattern finds a char other than a digit or letter in the input string and returns a match then.
You need a regex that matches an entire string made of letters or digits. Thus, you may use
let linkRegexPattern = "^[a-zA-Z0-9]*\\z"
It matches
^
- start of string[a-zA-Z0-9]*
- 0+ letters or digits\z
- the very end of the string.