show validation error messages on submit in angularjs

前端 未结 13 765
别那么骄傲
别那么骄傲 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:45

    Try this code:

    <INPUT TYPE="submit" VALUE="Save" onClick="validateTester()">
    

    This funvtion will validate your result

    function validateTester() {
        var flag = true
        var Tester = document.forms.Tester
        if (Tester.line1.value!="JavaScript") {
            alert("First box must say 'JavaScript'!")
            flag = false
            }
        if (Tester.line2.value!="Kit") {
            alert("Second box must say 'Kit'!")
            flag = false
            }
        if (flag) {
            alert("Form is valid! Submitting form...")
            document.forms.Tester.submit()
            }
        }
    
    0 讨论(0)
  • 2020-11-28 02:51

    A complete solution to the validate form with angularjs.

    HTML is as follows.

    <div ng-app="areaApp" ng-controller="addCtrler">
            <form class="form-horizontal" name="fareainfo">
                <div class="form-group">
                      <label for="input-areaname" class="col-sm-2 control-label">Area Name : </label>
                      <div class="col-sm-4">
                          <input type="text" class="form-control" name="name" id="input-areaname" ng-model="Area.Name" placeholder="" required>
                          <span class="text-danger" ng-show="(fareainfo.$submitted || fareainfo.name.$dirty) && fareainfo.name.$error.required"> Field is required</span>
                      </div>
                </div>
                 <div class="col-sm-12">
                      <button type="button" class="btn btn-primary pull-right" ng-click="submitAreaInfo()">Submit</button>
                 </div>
            </form>
        </div>
    

    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.

    0 讨论(0)
  • 2020-11-28 02:55

    http://jsfiddle.net/LRD5x/30/ A simple solution.

    HTML

    <form ng-submit="sendForm($event)" ng-class={submitted:submitted}>
    

    JS

    $scope.sendForm = function($event) {
      $event.preventDefault()
      $scope.submitted = true
    };
    

    CSS

    .submitted input.ng-invalid:not(:focus) {
        background-color: #FA787E;
    }
    
    input.ng-invalid ~ .alert{
        display:none;
    }
    .submitted input.ng-invalid ~ .alert{
        display:block;
    }
    
    0 讨论(0)
  • 2020-11-28 02:56

    I also had the same issue, I solved the problem by adding a ng-submit which sets the variable submitted to true.

    <form name="form" ng-submit="submitted = true" novalidate>
    <div>
        <span ng-if="submitted && form.email.$error.email">invalid email address</span> 
        <span ng-if="submitted && form.email.$error.required">required</span>
        <label>email</label>
        <input type="email" name="email" ng-model="user.email" required>
    </div>
    
    <div>
        <span ng-if="submitted && form.name.$error.required">required</span>
        <label>name</label>
        <input type="text" name="name" ng-model="user.name" required>
    </div>
    
    <button ng-click="form.$valid && save(user)">Save</button>
    </form>
    

    I like the idea of using $submitted, I think I've to upgrade Angular to 1.3 ;)

    0 讨论(0)
  • 2020-11-28 02:56

    I can come up with 2 ways to achieve it.

    The first one is to remove novalidate to enable the browser's validation.

    Second, you can disable the save button when the form is not valid like this

    <input ng-disabled="!frmRegister.$valid" type="submit" value="Save" />
    

    Hope it helps.

    0 讨论(0)
  • 2020-11-28 02:58

    G45,

    I faced same issue , i have created one directive , please check below hope it may be helpful

    Directive :

        app.directive('formSubmitValidation', function () {
    
            return {
                require: 'form',
                compile: function (tElem, tAttr) {
    
                    tElem.data('augmented', true);
    
                    return function (scope, elem, attr, form) {
                        elem.on('submit', function ($event) {
                            scope.$broadcast('form:submit', form);
    
                            if (!form.$valid) {
                                $event.preventDefault();
                            }
                            scope.$apply(function () {
                                scope.submitted = true;
                            });
    
    
                        });
                    }
                }
            };
    
    
      })
    

    HTML :

    <form  name="loginForm" class="c-form-login" action="" method="POST" novalidate="novalidate" form-submit-validation="">
    
    <div class="form-group">
                                                    <input type="email" class="form-control c-square c-theme input-lg" placeholder="Email" ng-model="_username" name="_username" required>
                                                    <span class="glyphicon glyphicon-user form-control-feedback c-font-grey"></span>
                                                    <span ng-show="submitted || loginForm._username.$dirty && loginForm._username.$invalid">
                                                        <span ng-show="loginForm._username.$invalid" class="error">Please enter a valid email.</span>
                                                    </span>
                                                </div>
    <button type="submit" class="pull-right btn btn-lg c-theme-btn c-btn-square c-btn-uppercase c-btn-bold">Login</button>
    </form>
    
    0 讨论(0)
提交回复
热议问题