Skip to content

Instantly share code, notes, and snippets.

@jspahrsummers
Last active December 17, 2015 21:39
Show Gist options
  • Save jspahrsummers/5676550 to your computer and use it in GitHub Desktop.
Save jspahrsummers/5676550 to your computer and use it in GitHub Desktop.
More complex RAC form validation
// Check name validity
RACSignal *nameValid = [RACAbleWithStart(self.name) map:^(NSString *name) {
return @(name.length > 0);
}];
RACSignal *nameValidationMessage = [nameValid map:^ id (NSNumber *valid) {
return valid.boolValue ? nil : @"Please enter a name that matches our bullshit rules";
}];
// Check email validity
RACSignal *emailMatches = [RACSignal combineLatest:@[ RACAbleWithStart(self.email), RACAbleWithStart(self.confirmEmail) ] reduce:^(NSString *email, NSString *confirmEmail) {
return [email isEqual:confirmEmail];
}];
RACSignal *emailValidationMessage = [emailMatches map:^ id (NSNumber *matches) {
return matches.boolValue ? nil : @"Both email addresses must match";
}];
// Populate the error message field
RAC(self.errorString) = [[RACSignal
combineLatest:@[ nameValidationMessage, emailValidationMessage ]]
// -map: is used here instead of a reduce block so that the logic extends
// to an arbitrary number of combined signals.
map:^(RACTuple *messages) {
return [messages.rac_sequence objectPassingTest:^ BOOL (NSString *message) {
return message != NSNull.null;
}];
}];
// Determine whether the form is valid
RAC(self.valid) = [[RACSignal
combineLatest:@[ nameValid, emailMatches ]]
map:^(RACTuple *validChecks) {
BOOL allValid = [validChecks.rac_sequence all:^(NSNumber *isValid) {
return isValid.boolValue;
}];
return @(allValid);
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment