angular form validation

1. create a html file like as below

<!-- index.html -->

<!DOCTYPE html>
<html>
<head>
    <!-- CSS ===================== -->
    <!-- load bootstrap -->
   
    <style>
    body { padding-top:30px; }
    </style>
    
    <!-- JS ===================== -->
    <!-- load angular -->
    <script src="../angular.js"></script> 
    <script src="app.js"></script>
</head>


<!-- apply angular app and controller to our body -->
<body ng-app="validationApp" ng-controller="mainController">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
    
    <!-- PAGE HEADER -->
    <div class="page-header"><h1>AngularJS Form Validation</h1></div>
   
    <!-- FORM -->
    <!-- pass in the variable if our form is valid or invalid -->
    <form name="userForm" novalidate > <!-- novalidate prevents HTML5 validation since we will be validating ourselves -->


        <!-- NAME -->
        <div class="form-group2" >
            <label>Name</label>
            <input type="text" name="name"  ng-model="name" required> *  
<label ng-show="(userForm.name.$invalid && !userForm.name.$pristine ) || (submitted && userForm.name.$error.required)">required</label>           
        </div>

    

      <!-- $pristine = ng-pristine -> form/input element has not  been used yet

            $dirty = ng-dirty -> form/input element has already been used

            $invalid  = ng-invalid -> form/input element is invalid

            $valid = ng-valid -> form/input element is valid

     -->

  


        <!-- USERNAME -->
        <div class="form-group">
            <label>Username</label>
            <input type="text" name="username" class="form-control" ng-model="user.username" required >
        </div>
        
       
        
        <!-- SUBMIT BUTTON -->
        <button name="submit"  ng-click="submitForm(userForm.$valid)" class="btn btn-primary">Submit</button>
        
    </form>


</div><!-- col-sm-8 -->
</div><!-- /container -->
</body>

</html>


2. create js file like as below

/* ------------------------app.js -------------------  */

// create angular app
var validationApp = angular.module('validationApp', []);


// create angular controller
validationApp.controller('mainController', function($scope) {


  // function to submit the form after all validation has occurred
  $scope.submitForm = function() {
     $scope.submitted=true;   // form will validate after click "submit" button
// check to make sure the form is completely valid
if ($scope.userForm.$valid) {

alert('our form is amazing');

    }else{

       alert("please input required fields");
  
    }
   };
});




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值