swiftvalidatorcommunity / swiftvalidator Goto Github PK
View Code? Open in Web Editor NEWA rule-based validation library for Swift
License: MIT License
A rule-based validation library for Swift
License: MIT License
Hello, I'm currently using this cool librairy but found something which seems strange to me.
There is a working PhoneNumber-Validator, but it's not usable rightnow because the class is not marked as public. I changed it locally, but maybe this should be fixed on your side, otherwhise the next release will overwrite my changes.
Greetings
Hi, here in my work, we started using this library, and then, we added support for some inputs beyond than just UITextField
, like: UITextView
, UISegmentedControl
and UIStepper
:
public var textFieldErrors:[UITextField:ValidationError] = [:]
public var textViewErrors:[UITextView:ValidationError] = [:]
public var segmentedControlErrors:[UISegmentedControl:ValidationError] = [:]
public var stepperErrors:[UIStepper:ValidationError] = [:]
public var textFieldValidations:[UITextField:ValidationRule] = [:]
public var textViewValidations:[UITextView:ValidationRule] = [:]
public var segmentedControlValidations:[UISegmentedControl:ValidationRule] = [:]
public var stepperValidations:[UIStepper:ValidationRule] = [:]
...
Now we are moving to iOS 9 and would like to get the latest SwiftValidator and merge what we have done so far.
My question is: a PR with these changes would be welcome?
Thanks.
For some reason other rules work, but this one doesn't.
validator.registerField(emailField, rules: [RequiredRule(), EmailRule()])
validator.registerField(passwordField, rules: [RequiredRule(), MinLengthRule(length: 6)])
If I create a float rule like this:
validator.registerField(textField, rules: [FloatRule()])
And then enter "sdfklnslfd", validation fails. But if I add "64565", so the resulting string in textfield is "sdfklnslfd64565" validation completes with success.
Hi great lib :)
There is an issue with the order returned by the func validationFailed
func validationFailed(errors:[UITextField:ValidationError]) {
// turn the fields to red
for (field, error) in validator.errors {
field.layer.borderColor = UIColor.redColor().CGColor
field.layer.borderWidth = 1.0
error.errorLabel?.text = error.errorMessage // works if you added labels
error.errorLabel?.hidden = false
}
}
For example if a register this fields:
FirsName
LastName
Email
Phone
Age
I expect the order of the errors in the same way, but it does not return in the same order, so the first error could be Email, and after FirstName, etc..
Is there any quick fix for this?
Hi,
PhoneNumberRule Rule class is not public so is not possible to use it when installing the lib via Cocoapods, and I think the pod version needs to be updated as well.
Best regards!
I have not been doing as much Swift and feel like I am neglecting this library. If you are interested in becoming a contributor please comment on this issue. Thanks!
It can be common to put an "age gate" on a signup form. I'm currently using a switch element for this. It would be useful to be able to add a validation rule that checks switch.on == true
. I'm going to check that in the validationSuccessful delegate method before I submit the form but that doesn't give me the ability to have the validationFailed delegate method handle the error case for me.
If I can find the time, I may try to do this myself and will send a pull request if I do but wanted to register this in case others have a similar need or the time to implement.
Thanks for sharing this framework!
Would be cool to see real time validation where the boxes turn green when the field has valid data.
Looks great! Nice job Jeff
Since I updated my xcode to 6.3.1, I got this error message
/Users/MNurdin/Documents/iOS/xxxxx/Controllers/LoginViewController.swift:20:21: Use of unresolved identifier 'Validator'
Please advice. Is there any updated library for swift 1.2?
For autocomplete to work on the validationError and validationRule passed back to the transform functions SwiftValidator had to be imported into the callback's file. If the text field, error label, and error message were passed back instead to error and text field, error label passed back to success then that file wouldn't need to import the framework. The autocomplete on Validator().asdfasdf works without the import.
I've followed the directions in the README to install SwiftValidator, and it seems like SwiftValidator was successfully installed. However, when I try to import SwiftValidator
at the top of a view controller, a diagnostic appears that says No such module 'SwiftValidator'
. Is this an issue with the library? I've also tried import Validator
.
I'm using Xcode 7 beta 4 and Swift 2. So maybe the module name isn't recognized because Validator.swift
, etc won't compile with the Swift 2 compiler.
Hi, any current efforts on updating SwiftValidator to 2.0?
Great library and tool.
Small issue inside MinLengthRule.swift:
func validate(value: String) -> Bool {
if countElements(value) <= DEFAULT_MIN_LENGTH {
return false
}
return true
}
should be:
func validate(value: String) -> Bool {
if countElements(value) < DEFAULT_MIN_LENGTH {
return false
}
return true
}
Currently I try to use this library with Carthage but has no success since its not a Shared Scheme.
Let's take the case of an optional email address:
validator.registerField(emailTextField, rules: [EmailRule()]) // Note that there is no RequiredRule()
There should be no error when the email textfield is empty.
Maybe RequiredRule()
should be treated as a special case where, if not in the list of rules, all other rules are skipped? Or maybe have an OptionalRule
?
I have a textbox with a minimum length rule of 2. When I add 1 character and validate I get a red border as expected. When I add another character and validate, the border does not revert to black.
Also, is it possible to use UITextViewDelegate to validate the textbox when a user moves to the next textbox? I have tried to use textFieldDidEndEditing and textFieldShouldEndEditing and calling validate(self), but to no avail - the textboxes do not revert their border style when the rule is met.
Often only the errors are required, so you do not need validationSuccess() at all. But still, I am required to implement an empty function.
Hi, I am trying to use the Swift Validator but I keep getting an error saying that the AppDelegate.swift is declared twice. What i did was I added the Validator folder and the Validator.xcodeproj to the top level of my application. I would imagine because the compiler sees two declarations of AppDelegate.swift in my project, the compiler cannot see the difference between the two files. As a result, I tried to only include the Validator.xcodeproj into my project and removed the Validator folder from my project but the 'Validator' class is not being recognized. Any ideas on how to fix this?
I had to make a custom rule that combines MinLength and MaxLength, but I feel like it's a common case that should be supported by default.
Transition to setting values through the constructor instead of through Validation.validate(value:String)
Required(#message:String)
Password(#regexString:String)
Length(#minLength:Int, #maxLength:Int)
Here's the case I'm thinking about:
Two text fields: "driving license state", "driving license number". Validating a driving license number depends on the value of the driving license state, and there's no way to specify that at the moment.
I'm not too sure what the interface should be for such a case. Maybe something like this:
validator.addField(stateField, rules: [RequiredRule()])
validator.addField(licenseNumberField, rules: [RequiredRule(), DynamicRule({ value -> Bool in
guard let state = stateField.text else {
return false
}
return validateLicenseNumber(value, state: state)
})])
Hello, is there any option to order the errors in the Delegate dictionary the same way as the text fields were registered into the validator?
Hi,
I searched a lot for this. No solution :(
When I try to create a custom validator I get this error:
could not find an overload for init that accepts the supplied arguments
in DOBRule.swift
import SwiftValidator
class DOBRule: RegexRule {
static let regex = "^[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2}$"
convenience init(message : String = "Not a valid SSN"){
self.init(regex: DOBRule.regex, message : message)
}
}
Thanks
The .podspec
needs to be updated to a release that includes the most recent pull requests (e.g. custom error message additions).
func validate(value: String) -> Bool {
return countElements(value) > DEFAULT_MIN_LENGTH
}
So if the minimum is 6, and I have 6 characters, it should be valid, but isn't. Only 7 is valid in this example.
The correct should be to use >=
.
Parallel: the minimum wage is $7.25, so the least you can legally pay someone is $7.25, not $7.26.
validator.validate()
validationWillRun()
- #34validator.validationSuccessful()
or validator.validationFailed()
but make them optional - #44validationDidRun()
I was wondering about the reason to pass a delegate or callback for the validation. Maybe the reason is to be able to return either success or error.
Instead you could just return an optional error dictionary, so validation result can be easily handled using if let:
if let errors = validator.validate() {
// do sth with errors
} else {
// success
}
This is much more convenient than having to implement a delegate. A callback is similar, but this is better as I don't see any legitimate reason to use callbacks.
Then it's also possible to remove "errors" instance variable from Validator, don't see any advantage of this except maybe storing last possible error but the implementation has to be adjusted a bit for that.
For the result I also thought about using an Either enum, in Swift 2, but an optional is more convenient as it's possible to use if let directly on the result and the success state doesn't have any payload. Either may be more accurate signalising the possible results but it's less convenient, and the meaning of the optional should be obvious IMO.
Would it make sense to do this change? Or is there anything I'm missing?
If the change is welcome I can submit a PR (child of Swift 2 commit).
You can see the changes here ivnsch@5e9e922 (all tests passing)
It look like localisation of error messages is missing.
Hello all, I am new to swift development and I'd like to start off by saying thank you for your pod. My question is this; Is there an easy way to add a parameter for field icon? I.E. I'd like to have an icon next to the textfield that changes colors if invalid or valid
[!] The platform of the target Pods
(tvOS 9.0) is not compatible with SwiftValidator (3.0.1)
, which does not support tvos
.
When I pull down from pod install I am not able to call validator.validateField because that function doesn't exist in the code the pod pulled down.
The example of the phone number don't use the rule phoneNumber
validator.registerField(phoneNumberTextField, errorLabel: phoneNumberErrorLabel, rules: [RequiredRule(), MinLengthRule(length: 9)])
Do you have any example using phoneNumberRule? Because i am having some difficulties
I'd like to use it in my project but the validation classes appear to be mixed with a sample project. I already have a project and am going to have to go through and extract the files that I need so it may be better to put the library in it's own folder and the sample project referencing in another folder so that people can just dump this in their projects.
Hi,
Is there any plan to add validator for UITextView?!
Thank you
As per subject, I got this error message on this line of code
import Foundation
class PhoneNumberValidation: Validation {
let PHONE_REGEX = "^\\d{3}-\\d{3}-\\d{4}$"
func validate(value: String) -> (Bool, ValidationErrorType) {
if let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX) { //error here
if phoneTest.evaluateWithObject(value) {
return (true, .NoError)
}
return (false, .PhoneNumber)
}
return (false, .PhoneNumber)
}
}
Please advice. Thank you.
I want to use SwiftValidator without installing using cocoapods. How to do that?
I am using SwiftValidator for so long. Today suddenly Xcode is throwing build failed and showing error : "No such module 'SwiftValidator'"
I am using Xcode 6.4 (Swift 1.2). I installed Swift Validator using pod
pod 'SwiftValidator', '2.1.1'
Please help
im getting odd errors with one of the swiftvalidator delegate methods
i added swift validator to my podfile
podfile looks as follows
platform :ios, '8.0'
use_frameworks!
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'SwiftValidator', '2.1.1'
i imported swiftvalidator to my LoginViewController (which is a subclass of UIViewController) by declaring import SwiftValidator
my class is declared as
class LoginViewController: UIViewController, UIAlertViewDelegate, UITextFieldDelegate, ValidationDelegate {
I initialised let validator = Validator() at the top level of the class
i added validator.registerField(emailField, errorLabel: emailErrorLabel, rules: [RequiredRule(), EmailRule()]) to viewdidload
i added skeleton of validationSuccessful delegate method as follows
func validationSuccessful() {
// submit the form
println("validation success")
}
but when i add other delegate method ie validationFailed as follows
func validationFailed(errors: [UITextField : ValidationError]){
println("test")
}
i get the following build errors ...
Getting Duplicate interface definition for class 'AppDelegate' and
Property has a previous declaration
in the apps swift header file ie komunety-Swift.h
if i change the errors parameter in this delegate function ie to func validationFailed(errors: [UITextField : String] the error goes away ... ie it seems to be related to the ValidationError type itself
any ideas on how to fix
Noticed that this library needs to be updated for swift 1.2
Right now, validating with a callback looks like this:
validator.validate { errors in
}
Is there any reason to have the validation block based and not just declarative? Like this:
let errors = validator.validate()
It would be nice to have success/errors states for all the fields, so you could color each field depending on the validation status.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.