show validation error messages on submit in angularjs

前端 未结 13 837
别那么骄傲
别那么骄傲 2020-11-28 02:25

I have a form which need to show validation error messages if clicked submit.

Here is a working plunker

 
13条回答
  •  醉梦人生
    2020-11-28 02:51

    A complete solution to the validate form with angularjs.

    HTML is as follows.

    Field is required

    AngularJS App and Controller is as follows

    var areaApp = angular.module('areaApp', []); 
    areaApp.controller('addCtrler', function ($scope) {
        $scope.submitAreaInfo = function () {  
           if ($scope.fareainfo.$valid) {
             //after Form is Valid
           } else {
              $scope.fareainfo.$setSubmitted();
           }
        };
    });
    

    Important Code Segments

    1. ng-app="areaApp" ng-controller="addCtrler"
      Defines the angular app and controller

    2. ng-show="(fareainfo.$submitted || fareainfo.name.$dirty) && fareainfo.name.$error.required"
      Above condition ensure that whenever a user first sees the form there's no any validation error on the screen and after a user does changes to the form it ensure that validation message show on the screen. .name. is the name attribute of the input element.

    3. $scope.fareainfo.$valid
      Above code, segment check whether the form is valid whenever a user submits the form.

    4. $scope.fareainfo.$setSubmitted();
      Above code, segment ensures that all validation messages are displayed on the screen whenever a user submits the form without doing anything.

提交回复
热议问题