angular 1.2.16 - Form validation example

by miyukiw

HTML

<script src="https://code.angularjs.org/1.2.16/angular.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<div ng-app="TestApp" ng-controller="myCtrl" class="container">
    <h1>angular 1.2.16 Form validation example</h1>
    <div ng-form name='testForm'>
        <div my-input id="name" ng-model="formData.name" ng-required="true" placeholder="山田太郎" title="氏名"></div>
        <div my-input id="zip-code" ng-model="formData.zipCode" ng-required="true" placeholder="1234567" title="郵便番号" validation="patterns.zipCode"></div>
        <div my-input id="phone-number" ng-model="formData.phoneNumber" ng-required="true" placeholder="0312345678" title="電話番号" validation="patterns.phone"></div>
        <hr>
        <button class="button btn btn-primary btn-block" ng-disabled="testForm.$invalid">送信</button>
    </div>
</div>

JavaScript

angular.module('TestApp', [])
    .controller('myCtrl', ['$scope', function ($scope) {
    $scope.patterns = {
        zipCode: {
            regexp: '/^[0-9]{7}$/',
            msg: 'ハイフンなしの7桁の数字で入力してください',
            maxlength: 7
        },
        phone: {
            regexp: '/^[0-9]{10,11}$/',
            msg: 'ハイフンなしの半角数字を10〜11桁で入力してください',
            maxlength: 11
        }
    };
}])
    .directive('myInput', function () {
    return {
        restrict: 'A',
        require: ['^?form'],
        transclude: true,
        replace: true,
        scope: {
            title: '@',
            id: '@',
            ngModel: '=',
            ngRequired: '=',
            validation: '=',
            placeholder: '@?',
            errMsg: '=?'
        },
        controller: ['$scope', function ($scope) {
            // create error msg
            if (!$scope.errMsg) {
                $scope.errMsg = {};
            }
            if ($scope.ngRequired === true && !('required' in $scope.errMsg)) {
                $scope.errMsg.required = $scope.title + 'を入力して下さい';
            }
            if ($scope.validation && !('invalid' in $scope.errMsg)) {
                $scope.errMsg.invalid = $scope.validation.msg;
            }
        }],
        link: function (scope, element, attrs, ctrl) {
            scope.target = ctrl[0][attrs.id];
        },
        template: '<div class="field" class="form-group" ng-class="{\'has-error\': target.$dirty && target.$invalid}">' +
            '<label ng-bind="title" class="control-label"></label>' +
            '<input name="{{id}}" ng-model="ngModel" ng-required="ngRequired" ng-pattern="{{validation.regexp}}" maxlength="{{validation.maxlength}}" placeholder="{{placeholder}}" type="text" class="form-control" />' +
            '<div class="errors" ng-show="target.$dirty">' +
            '<p ng-bind="errMsg.required" ng-if="target.$error.required && errMsg.required"></p>' +
            '<p ng-bind="errMsg.invalid"...