The Spring framework offers a convenient way for iOS apps to validate inputs and create forms.
The “ios form validation best practices” is a framework that provides support for the iOS platform’s built-in form validation. It allows developers to use a single API to validate fields on both iPhone and iPad apps.
ATGValidator is a validation framework designed to handle the most frequent problems that arise while validating user input data.
You may use it to verify multiple data types directly, as well as UI components like UITextfield and UITextView, and even your own custom UI elements. To obtain validation support, you don’t have to subclass native components. Support for ValidatableInterface is built-in to UITextField and UITextView; adding support for additional components is as easy as providing an extension with protocol conformance to ValidatableInterface.
The best part is that you’ll receive a form validator that combines the validation results of every ui components you add to it.
a hypothetical project
A example project using form validation may be seen here.
Carthage may be used to install ATGValidator. Simply add the following line to your Cartfile to do this:
1.0.0 github “altayer-digital/ATGValidator”
Add the following line to the Podfile to utilize ATGValidator with cocoapods:
‘ATGValidator’, ‘> 1.0’ pod
Setting the validation rules on the ui element is the first step in adding validation. ValidatableInterface-compliant UI elements accept an array of rules.
textfield.validation CharacterSetRule.containsUpperCase(), CharacterSetRule.containsLowerCase(), CharacterSetRule.containsNumber(), CharacterSetRule.containsSymbols()] Rules = [CharacterSetRule.containsUpperCase(), CharacterSetRule.containsLowerCase(), CharacterSetRule.containsNumber(), CharacterSetRule
You may use a validationHandler closure on a textfield or textview to validate a single textfield or textview. This will be run once the field has been validated and the result is ready to be applied. If the validation fails, an array of errors is supplied with the result object.
result in print(result.status, result.errors) textfield.validationHandler = result in print(result.status, result.errors)
To execute validations on the respective events, use validateOnInputChange or validateOnFocusLoss on the ui element.
You must construct a FormValidator object and add all required items to the form validator if you need to aggregate validations of many ui elements.
formValidator.add(handler: result in print(result.status, result.errors)) let formValidator = FormValidator(handler: result in print(result.status, result.errors)) (textfield)
When you add an item to the form validator, validation is performed by default when the attention on that item is lost. However, by declaring validationPolicy while adding the item to the form validator, you may modify this behavior for particular fields.
add(textfield, policy:.onInputChange) / or.onFocusLoss or.none)
The form validator’s handler closure will be invoked with aggregated results whenever the fields have relevant state changes to their data.
If you wish to do validation on the fly, use the validateForm(shouldInvokeElementHandlers:completion:) function.
The framework comes with six different sorts of rules right out of the box. You may provide a custom error for all rules during initialization, or use the helper methods with(error:)->Rule or with(errorMessage:)->Rule to set it afterwards. If not, the ValidationError enum provides default errors for all rules. You’ll find them listed below, along with descriptions of each regulation.
This rule is used to see whether the type’s value matches the given value.
By giving the value to be verified against to the initializer, you may establish an equality rule. You may also provide the mode (equal, notEqual) and an error object to be returned if the validation fails.
let EqualityRule(value: “text to be verified”) be the rule / or let rule = EqualityRule(value: “shouldn’t be equal text”, mode:.notEqual, error: ValidationError.equal), value: “shouldn’t be equal text”)
Errors by default:
- For equal mode, there is a notEqual error.
- notEqual mode returns the same error.
This rule may be used to see whether a value is inside a certain range.
allow rangeRule to be equal to RangeRule (min: 200, max: 299)
valueOutOfRange is the default error.
This rule may be used to verify the length of a string. You may specify whether white spaces should be trimmed and if certain charactersets should be ignored.
let time to pass StringLengthRule(min: 5, max: 10, trim); inRangeRule = StringLengthRule(min: 5, max: 10, trim); inRangeRule = StringLengthRu True, but disregard the whitespace. CharactersIn: CharacterSet.symbols))))))))))))))))))))) allow min StringLengthRule = LengthRule min(5) allow maximum StringLengthRule = LengthRule max(5) equalize StringLengthRule = LengthRule let necessary equal(to: 6) StringLengthRule = StringRule required()
Errors by default:
- lengthOutOfRange is the default value.
- maximum length: ThanMaximumLength
- notEqual: equal
- shorterThanMinimumLength is necessary.
This rule enables you to match strings using regular expressions. You may choose whether or not to clip white spaces.
StringRegexRule(regex: “[0-9]*$”) let regexRule = StringRegexRule(regex: “[0-9]*$”) let emailRule = StringRegexRule.email let emailRule = StringRegexRule.email let emailRule = StringRegexRule. StringRegexRule.contains = Number Let’s see what Number() has to offer. StringRegexRule.contains = NumbersMinMax the number (min: 2, max: 4) consists of StringRegexRule.contains = UpperCase let UpperCase() contains StringRegexRule.contains UpperCaseMinMax = StringRegexRule.contains The UpperCase (min: 1, max: 2) consists of StringRegexRule.contains = LowerCase LowerCase() is a function that returns the case of a variable. StringRegexRule.contains = LowerCaseMinMax CaseLower (min: 1, max: 2) Allow the statistics to speak for themselves. StringRegexRule = StringRegexRule. numbers Allow just lowerCaseOnly = StringRegexRule to be true. upperCaseOnly = StringRegexRule lowerCaseOnly = StringRegexRule upperCaseOnly
Errors by default:
- regexMismatch is the default value.
- email address is invalid
- numberNotFound: containsNumber
- upperCaseNotFound: containsUpperCase
- lowerCaseNotFound: containsLowerCase
- onlynumbers: invalidType
- invalidType: lowerCaseOnly
- invalidType: upperCaseOnly
This rule may be used to see whether the values in two textfields are the same. When we verify whether the contents of the password field and the confirm password field are the same, this is an excellent example.
allowing password Is it UITextField or UITextField? Please confirm. UITextField or PasswordTextField? allow worth to exist StringValueMatchRule(base: passwordTextfield) confirm MatchRule = StringValueMatchRule(base: passwordTextfield) confirm PasswordTextfield.validation [valueMatchRule] = [valueMatchRule] = [valueMatchRule] = [
notEqual is the default error.
A payment card rule may be used to determine if a given card number is valid. The validity of the input card numbers is checked using Luhn’s technique in conjunction with regex matching. The rule may be started with a list of card kinds to check for, or it can be set to check for all possible card types if the first one fails. The following card kinds are available:
- American Express is a credit card company based in
- Visa Electron is a kind of credit card that is used
- Diners Club is a social club for those who like to
if cardRule = PaymentCardRule; if cardRule = PaymentCardRule; if card (acceptedTypes: [.amex, .mastercard, .visa, .discover]) / Alternatively, set cardRule to PaymentCardRule () [cardRule] textfield.validationRules = if let suggestedType = result.value as, textfield.validationHandler = result in PaymentCardType / This is a recommendation from the framework based on your input. / It’s important to remember that just because a card type is proposed doesn’t guarantee it’s legitimate. Outside of this constraint, you must handle success/failure individually. textfield.validateOnInputChange(true)
Errors by default:
- If the card number is invalid, use invalidPaymentCardNumber instead.
- If your card number is legitimate but not one of the allowed kinds, follow these steps: paymentCardNotSupported
Please utilize the value field in the Result object to determine the card type when filling in the number. The rule will fill the Result.value field with the card type if one can be recommended from the inputted input, else it will be populated with the input. Please note that a minimum of 4 characters must be input before the rule can begin to recommend card types.
As seen here, you can verify common data types right out of the box.
“A single-number example.” satisfyAll(rules: [CharacterSetRule.containsNumber()]) =============================== . “Example with more than 20 characters,” status / success satisfyAll(rules: [StringLengthRule.max(20)], satisfyAll(rules: [StringLengthRule.max(20)], satisfyAll(rules: [Str . failure is the state 472.satisfyAll(EqualityRule(value: 472.5)]) / failure 301.satisfyAny(rules: [RangeRule(min: 200, max: 299), EqualityRule(value: 304)], EqualityRule(value: 304)]) / failure 200.satisfyAny(rules: [RangeRule(min: 200, max: 299), EqualityRule(value: 304)], EqualityRule(value: 304)]) / achievement
Please see the example below for verifying the contents of an ui component.
textfield.validation [CharacterSetRule.lowerCaseOnly(ignoreCharactersIn:.whitespaces)] Rules = [CharacterSetRule.lowerCaseOnly(ignoreCharactersIn:.whitespaces)] When validation is performed, textfield.validationHandler = result in / This block will be run with the appropriate result. success / print(result.status) The line below is used to manually start validation. textfield.validateTextField()
To utilize the form validator, we must first build a FormValidator object and then add the appropriate ui components to it. We can either use the validateForm function directly or attach a handler closure to the form validator that will be invoked whenever the value of any of the additional ui elements changes.
FormValidator should be set to FormValidator () add(textfield) in formValidator / More ui components should be added here. result in print(result) from formValidator.validateForm
Validatable is the foundation protocol that every data type that can be validated must follow. Most widely used Swift types are Validatable right out of the box. The following is a list of all data types that are Validatable out of the box.
Validation functionality may be added to any other type by conforming it to the validatable protocol.
Validation must be supported by any custom UI element that follows the ValidatableInterface protocol. ATGValidator has introduced this compliance to UITextField and UITextView out of the box. It’s worth noting that the ValidatableInterface interface is compatible with the Validatable protocol. Please check the UITextField example below to see how the compliance should be implemented.
ValidatableInterface is an extension for UITextField. Any return text?? “” public var inputValue: validateOnInputChange(_ validate: Bool) is a public func. If valid, addTarget(self, action: #selector(validateTextField), for:.editingChanged) else removeTarget(self, action: #selector(validateTextField), for:.editingChanged) public func validateOnFocusLoss(_ validate: Bool) public func validateOnFocusLoss(_ validate: Bool) public func validateOnFo if validate, addTarget(self, action: #selector(validateTextField), for:.editingDidEnd) if not, removeTarget(self, action: #selector(validateTextField), for:.editingDidEndOnExit) if not, removeTarget(self, action: #selector(validateTextField), for:.editingDidEndOnExit guard let rules = validation @objc public method validateTextField() Return if the rules don’t apply. satisfy as a variable If result, all(rules: rules) == status == success if let value = validValue, result.value = value; else, if let value = validValue, result.value = value validation (result) form of the handler ‘Handler?’ (result) ‘Handler?’ ‘Handler?’ ‘Handler?
Errors that are unique to you
ValidationError is an enum that contains all validation failures by default. Use ValidationError.custom(errorMessage: Text) if you don’t want to construct an extra error object and simply require a custom validation error string to be supplied. In Rule, there are a few assist methods for quickly setting custom errors. The following is a list of them:
emailRule = StringRegexRule; var emailRule = StringRegexRule; var emailRule = StringRegex with(error: CustomErrorThatConformsToErrorProtocol()) email emailRule = emailRule.with(error: CustomErrorThatConformsToErrorProtocol()) email emailRule = emailRule.with(error: CustomErr or emailRule = emailRule.with(errorMessage: “Email is incorrect…”)
This is a special in-memory storage location for the closures of all rules, form handlers, and validation handlers. Please feel free to look into how it’s done.
When we were looking for a suitable validation framework to employ in our projects, we went through the research stage of looking for existing opensource libraries before settling on the best one for the job. You’d know which one it is if you were in the same circumstances. It’s none other than Adam Waite’s fantastic Validator framework. If you haven’t already done so, please go to that repo and have a look.
Validator makes considerable use of generics and is the framework’s backbone. We were unable to group together diverse ui components and get a consistent result for the validations as a consequence of this. And form validation was critical in our initiatives.
As a result, we began developing a framework using protocols as its foundation and form validation as the primary purpose. And now, ATGValidator, here’s the end result. Please note that the Validator framework greatly impacted the basic principles, and we wish to give Adam Waite credit for his outstanding work.
Copyright and Permissions
ATGValidator is open-source software licensed under the MIT license. For further information, see LICENSE.md.
A list of contributors may be seen on GitHub.
The “validation swift” is a framework that allows for form validation support on iOS. The framework was released by Apple and the project is maintained by the Swift team.
- uitextfield validation error message swift
- swiftui form validation
- text field validation in swift 4
- swift validation rules
- swift validator github