2016-08-09 16 views
0

私はページに2つの必須フィールドを表示する必要があります。私はdatePatternと必要なフィールドチェックを持っています。角度jsでのサブミット時に必須のフィールド検証

フィールドを入力することなく、送信時にフィールドが必要です。私が何かを入力すると、私のdatePatternは正常に動作します。

Ng-show = Form.field1。$ error.required & & Form.field1。$ pristineのように表示する場合に必要です。これは開始時に必要なメッセージを表示しますが、私は送信時にこのフィールドを編集する必要があります。フィールドdatePatternを編集するとこれは問題ありません。

私はng-click = submitted = trueを試しました。そして、NG-提出= ctrl.submit()、それはコントローラに入っていない...

いくつかのいずれかの助け...

答えて

0
<form ng-submit="validateForm()"> 
    <input ng-model="name"> 
    <span ng-show="invalidName">Please fill name field</span> 
</form> 

controller('MyController', function ($scope){ 

    $scope.validateForm = function(){ 
    if($scope.name){ 
     $scope.invalidName = true; 
    } 

    if($scope.invalidName){ 
     //Prevent submit 
     return false; 

    }else{ 
     //Handle submit here or do nothing for auto submit of form 
    } 


    }; 

}); 
+0

私のコントローラから設定したくない – Satheesh87

0

が、私はこれを処理する方法(それが最良の方法であることなし約束する)ことができます私はそれぞれのフォームフィールドを$ touchedに設定し、フィールドごとに$ errorと$ touchになったときに警告を表示します。

jsfiddle

HTML

<div ng-app="app" ng-controller="ctrl"> 
    <div ng-form="forms.datesForm"> 
    <input type="text" ng-model="date" name=date required /> 
    <p ng-show="forms.datesForm.date.$touched && forms.datesForm.date.$invalid">Please select a date.</p> 
    <br /> 
    Your date: {{date}} 
    <button ng-click="submitForm()">Submit</button> 
    </div> 
    <p ng-show="submitted"> 
    Congrats, you submitted successfully! 
    </p> 
</div> 

JS

angular.module('app', []); 

angular.module('app').controller('ctrl', ['$scope', function ($scope) { 

    $scope.forms = {}; 

    $scope.submitForm = function() { 
    if ($scope.forms.datesForm.$invalid) { 
     setAllFieldsTouched($scope.forms.datesForm); 
     return; 
    } 
    else { 
     // do whatever submit logic here 
     $scope.submitted = true; 
    } 
    } 

    var setAllFieldsTouched = function() { 
    // loop through all the empty required fields 
    angular.forEach($scope.forms.datesForm.$error.required, function (field) { 
     // only forms have $submitted properties, not fields 
     if (field.hasOwnProperty('$submitted')) { // is a form, recur through it 
     setAllFieldsTouched(field); 
     } 
     else { // this is a field 
     field.$setTouched(); 
     } 
    }); 
    } 
}]); 
+0

考えてくれてありがとう。しかし、私はフィールドに触れることはありませんし、それから提出してくださいフィールドは、条件の下で必要なチェックアウトを参照する必要があります – Satheesh87

+0

Ngのショー=フォーム。$提出&& form.field1。$ error.requiredこれはどう? – Satheesh87

+0

フィールドをクリックして記入せずに残しても表示されません。あなたの最初のコメントでどういう意味ですか、私はかなり理解していませんか? – Bob

1

私は

フォームをこのように固定。$ & & form.field1を提出しました。$ error.required &を!form.field1。$ touched

関連する問題