/angularjs/

AngularJS – Base Form Validation

2014-06-08 12:30:17

<!DOCTYPE html>

<html lang='"en"' ng-app='"szalekApp"'>
<head>
<title>Angular Form</title>
<link href='"lib/bootstrap/css/bootstrap.min.css"' rel='"stylesheet"'/>
</head>
<style type='"text/css"'>
    input.ng-invalid.ng-dirty {
        border: 2px solid red;
    }

    input.ng-valid.ng-dirty {
        border: 2px solid green;
    }
</style>
<body>
<section class='"container"' ng-controller='"FormController"'>
<form name='"myform"' novalidate="">

        Name:
        <input class='"form-control"/' ng-model='"user.name"' required="" type='"text"'/>

        Email:
        <input class='"form-control"/' ng-model='"user.email"' type='"email"'/>

        MinMaxlength:
        <input class='"form-control"/' maxlength='"20"' ng-model='"user.minMaxlength"' type='"text"'/>

        MinMax:
        <input class='"form-control"/' max='"40"' min='"10"' ng-model='"user.minMax"' type='"number"'/>

        Url:
        <input class='"form-control"/' ng-model='"user.url"' type='"url"'/>
<button ng-click='"update(user)"'>SAVE</button>
</form>

    Log:
    <pre>{{user | json}}</pre>

    IsValid:
    <pre>{{myform.$valid}}</pre>
</section>
</body>
<script src='"lib/angular.min.js"'></script>
<script src='"app/app.js"'></script>
</html>

var app = angular.module('szalekApp', []);

app.controller('FormController', function ($scope) {

    $scope.user = {};

    $scope.update = function () {
        if ($scope.myform.$valid) {
            console.log("Saved: ");
            console.log($scope.user);
        } else {
            console.log("Problem with: ");
            console.log($scope.user);
        }
    };
});