escoz/QuickDialog — pull request #63 by kcoop (2012-02-09 21:41:33+00:00)
Title: Basic validation

I've started using QuickDialog and found it very helpful. Thanks for putting this up!

I've had a need for validation, so put together a bare-bones process to handle it and thought you might want to add it to the base project. It is relatively lightweight - adds a single instance variable to QElement.

To use it, you simply call validate: on your root element, and it returns a list of error strings for all the fields that failed. For example:

NSMutableArray *errors = [[NSMutableArray alloc]init];
[self.root validate: errors];
if (errors.count > 0) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please Fix"
message: [errors objectAtIndex:0]
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
return NO;
}

Here's how it's declared:

QEntryElement *passwordEntry = [[QEntryElement alloc] initWithTitle:@"Password" Value: nil];
passwordEntry.key = @"password";
...
passwordEntry.validator = [QEntryValidator requiredField:@"Password is required"];

and here's an email field:

QEntryElement *emailEntry = [[QEntryElement alloc] initWithTitle:@"Email" Value:nil Placeholder:@"example@example.com"];
...
emailEntry.validator = [QEntryValidator emailField:@"A valid email address is required"];

Right now it just supports requiredFields, emailFields, and generic regex matching for QEntryElements, but it's intended to be extended by subclassing QValidator, and I expect to add more standard regexs, like valid user names and passwords.

The validate: method does not do any UI magic - just returns that list of error strings to the caller.