sasrra
sasrra

Reputation: 87

Required field validation on submit in angular js

I have a requirement of displaying two required fields on page. I have a datePattern and required field check.

I need to display field is required on submit without entering fields . If I enter something my datePattern works fine. Since it is required when I display like

Ng-show = Form.field1.$error.required && Form.field1.$pristine. This displays required message on start but I want this on submit and once I edit my field datePattern comes into picture this is fine.

I have tried ng-click=submitted = true. And ng-submit=ctrl.submit() it's not entering into controller..

Can some one help...

Upvotes: 0

Views: 1492

Answers (3)

sasrra
sasrra

Reputation: 87

I fixed this way

Form.$submitted && form.field1.$error.required && !form.field1.$touched

Upvotes: 1

Bob
Bob

Reputation: 31

The way I handle this (no promises that it is the best way) is that on the submit function I set each form field to $touched, then for each field I show the warning when the field is $error and $touched.

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();
      }
    });
  }
}]);

Upvotes: 0

Jijeesh
Jijeesh

Reputation: 26

<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 
    }


   };

});

Upvotes: 0

Related Questions