2017-01-03 142 views
0

我試圖驗證我的表單,如果這些字段是有效的,那麼它應該將數據發佈到數據庫,如果不阻止將數據發佈到數據庫。當我提交表格我得到一個錯誤TypeError: Cannot read property '$valid' of undefined,我不知道如何克服它,需要幫助。表單驗證使用angularjs

HTML:

<form name="formvalidation"> 
<ion-view ng-controller="ValidationCheck"> 
<ion-content> 
<div> 
<strong>User:</strong> <br/> 
<input ng-model="name" type="text" name="name" required/> 
<ng-messages for="formvalidation.name.$error" ng-if="formvalidation.name.$invalid"> 
<div ng-messages-include="error/validation.html"></div> 
<ng-messages> 
</div> 
</from> 
<button ng-click="check()"> 

控制器:

myApp.controller('ValidationCheck',function($scope, applicationService) 
{ 
$scope.check=function(formvalidation){ 
var name={'name'=$scope.name}; 
$scope.submitted=true; 
if(formvalidation.$valid){ 
applicationService.save(name,$scope.home); 
}}}); 

回答

1

只要改變你的,如果條件formvalidation.$validformvalidation 。因爲您已通過formvalidation.$valid在您的功能中通過ng-click

if(formvalidation){ 
... 
... 
... 

} 
0

刪除NG單擊並添加NG提交:

<form name="formvalidation" ng-submit="check()" novalidate> 
0

試試這個:(控制器在f之前ORM)

<ion-view ng-controller="ValidationCheck"> 
     <form name="formvalidation"> 
0

在你的HTML您有:

<button ng-click="check(formvalidation.$valid)"> 

與無論是真或假的值(一個布爾調用檢查功能),這取決於窗體是否在有效。

在您的控制器必須與校驗功能以下if語句:

if(formvalidation.$valid) 

但formvalidation是一個布爾值(true或false)

我建議從檢查和簡單的訪問參數$ scope變量的formvalidation屬性。

使HTML變得

<button ng-click="check()"> 

和控制器變成

$scope.check=function(){ 
    var name={'name'=$scope.name}; 
    $scope.submitted=true; 
    if($scope.formvalidation.$valid) { 
     applicationService.save(name,$scope.home); 
    } 
} 
0

<form>應該來控制器聲明之後

<div ng-app="app"> 
    <ion-view ng-controller="ValidationCheck"> 
    <form name="formvalidation"> 
     <ion-content> 

var app = angular.module("app", []); 
 
app.controller('ValidationCheck', function($scope) { 
 
    $scope.check = function(formvalidationBoolean) { 
 
    alert(formvalidationBoolean); 
 
    var name = { 
 
     'name': $scope.name 
 
    }; 
 
    $scope.submitted = true; 
 
    if (formvalidationBoolean) { 
 
     //applicationService.save(name, $scope.home); 
 
    } 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="app"> 
 
    <ion-view ng-controller="ValidationCheck"> 
 
    <form name="formvalidation"> 
 
     <ion-content> 
 
     <div> 
 
      <strong>User:</strong> 
 
      <br/> 
 
      <input ng-model="name" type="text" name="name" required/> 
 
      <ng-messages for="formvalidation.name.$error" ng-if="formvalidation.name.$invalid"> 
 
      <div ng-messages-include="templates/admin/validation.html"></div> 
 
      <ng-messages> 
 
     </div> 
 
     </from> 
 
     <button ng-click="check(formvalidation.$valid)">Submit</button> 
 
</div>

  1. 您發送布爾值"ng-click="check(formvalidation.$valid)",所以你的發言if(formvalidation.$valid){內部控制是錯誤的。
  2. ,你需要改變 「=」 要 「:」 在var name = {'name': $scope.name };