This a bit of a simple one, but one that I end up looking up all the time.

Say you have a text field, but it is saved in your model as a NSNumber. Before conversion, you need to ensure the user has entered in a number and not something silly like ‘cow’.

What we are going to do here is have our text field pop up an alert box if the user has entered in anything but a number.

Firstly, build your screen in the usual manner, and in the ‘save’ function that is called to take data from your text fields, add in this:

    //Add a boolean for every field you want to validate against.  In this case I have 2 number fields.
    BOOL targetValid = false, milestonesValid= false;
    //This defines a character set that contains all the valid characters - numbers.
    NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet];
    //Convert what we have in the text field to a NSCharacterSet
    NSCharacterSet *targetString = [NSCharacterSet characterSetWithCharactersInString:target.text];
    //If our gathered characters are a subset of the numbers set, then the field is valid
    targetValid = [alphaNums isSupersetOfSet:targetString];
    //Repeat for our other field
    NSCharacterSet *milestonesString = [NSCharacterSet characterSetWithCharactersInString:milestones.text];
    milestonesValid = [alphaNums isSupersetOfSet:milestonesString];
    if (!targetValid || !milestonesValid){
        NSMutableString *errors = [[NSMutableString alloc] init];
        //Check which errors we have and append an error message in each case
            [errors appendFormat:@"Target must be a numbern"];
            [errors appendFormat:@"Measurements must be a numbern"];
        //Pop up an alert notifying the user of what textFields have errors
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Errors" message:errors delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
        [alertView show];
//.....otherwise carry on saving information within the form

Thats all there is to it! If you want to get more fancy with alerts, there is a callback method that gets triggered when you close the alert. An example of this is:

/* Somewhere in your code, an alert like this:
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Edit", @"Submit", nil] autorelease];
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
   //In the above example we have set the alert to have a tag of 3 - lets test for it here in case there are
   // Other alerts that may be using this callback
   if(alertView.tag ==3){
       if (buttonIndex == 0) {     // user clicked Cancel.
       if (buttonIndex == 1) {     // user clicked Edit.
       if(buttonIndex == 2){       //User clicked Submit