Form Validation Using AngularJS

A common use case for client side form validation is this:

  1. After the form is submitted, show all invalid input fields using a special color.
  2. If the form is invalid then do not take any action.

AngularJS documentation on form does a good job explaining how to highlight an invalid input field after it gains and loses keyboard focus. But it doesn’t show how to do that for all invalid input fields (irrespective of if it gained input focus) and only after the form is submitted.

Also, in many cases, you will be asked to highlight a div that surrounds an input field and not the input field itself. AngularJS applies styles like ng-invalid to the input field itself and hence will not meet that requirement.

Showing Error Highlight

First, we will write a controller method that will determine if error highlight should be shown for an input field. It will go something like this:

$scope.showError = function(inputName) {
  var form = $scope.myForm;

  return (form.$submitted || form[inputName].$touched) && 
    !form[inputName].$valid;
}

Basically it returns true if the field is invalid and only if the field lost focus or the form was submitted.

Create a style to highlight invalid input.

input.error {
      background: red;
}

In the HTML template use the class if error highlight should be shown.

<form name="myForm" novalidate>
  <input type="text" ng-model="user.name" name="uName" 
    ng-class="{error: showError('uName')}" required="" />
</form>

You can also show an error message if you like:

<input type="text" ng-model="user.name" name="uName" 
    ng-class="{error: showError('uName')}" required="" />
<br />
<div ng-show="showError('uName')">Tell us your name.</div>

Is the Form Valid?

To see if the form is completely valid use the $valid property of the form. It will be set to false if at least one input field in the form is invalid. An example form submit handler will look like this:

$scope.update = function() {
      console.log("Form submitted");
      if ($scope.myForm.$valid) {
        console.log("The form is valid.");
      } else {
        console.log("Form is invalid");
      }
};

See a working example in Plunker.

Advertisements

Facebook Login Using Native iOS API

Introduction

If you want to add Facebook login support to your app, you have two main choices:

  • Use the native account management support built into iOS.
  • Use the API available from Facebook.

In this article I will explain how to use the first option. It has a few advantages:

  • User has to login to Facebook only once from the iOS Settings app.
  • There is no third party library to download and add to your app.

Register Your App

Go to http://facebook.com/developer and register your iOS app. You will need to supply the bundle ID of your app. You can get that from Xcode by selecting your target.

image

After you register the app, you will receive an application ID which is a large integer number.

image

We will need to use this app ID later.

Create the Facebook Account

Launch the iOS Settings app and click Facebook.

images

Log in to Facebook from there to add the account to your device.

Login from Your App

In your view controller’s header file, add two properties.

@import Accounts;

@interface ViewController : UIViewController

@property (nonatomic, strong) ACAccountStore *accountStore;
@property (nonatomic, strong) ACAccount *facebookAccount;

@end

In the view controller class, add this method.

-(void) facebookLogin
{
    NSLog(@"Trying to access FB account.");

    self.accountStore = [[ACAccountStore alloc]init];
    ACAccountType *FBaccountType= [self.accountStore 
        accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

    NSString *appID = @"1540000000000031"; //The app ID issued by Facebook
    NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:
                            appID, ACFacebookAppIdKey,
                            @[@"email"], ACFacebookPermissionsKey,
                            nil];

    [self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
     ^(BOOL granted, NSError *e) {
         if (granted)
         {
             NSArray *accounts = [self.accountStore accountsWithAccountType:FBaccountType];
             //it will always be the last object with single sign on
             self.facebookAccount = [accounts lastObject];


             ACAccountCredential *facebookCredential = [self.facebookAccount credential];
             NSString *accessToken = [facebookCredential oauthToken];
             NSLog(@"Successfully logged in. Access Token: %@", accessToken);
        } else {
             //Failed
             NSLog(@"error getting permission: %@",e);
         }
     }];
}

Note that the login happens asynchronously. You must save the ACAccountStore object as a property. Otherwise it will go out of scope and get destroyed.

Finally, call the method from viewDidLoad.

- (void)viewDidLoad {
    [super viewDidLoad];
    //Login to Facebook
    [self facebookLogin];
}