简体   繁体   中英

Display validation message on submitting the form in Angularjs

I want to display validation message after user clicks on the submit form. Eg Text box is required and user directly clicks on the submit button then the validation field should be displayed.

Here when the user clicks on the form nothing happens.

<body ng-controller="AppController as ctrl">

<form ng-submit="ctrl.submit()" name="myForm" novalidate>
    <input type="text" ng-model="ctrl.user.username" name="uname" class="username" placeholder="Enter your name" required ng-minlength="3" />
    <span ng-show="myForm.$dirty && myForm.uname.$error.required">This is a required field</span>

    <input type="text" ng-model="ctrl.user.address" placeholder="Enter your Address" /><br /><br />

    <input type="email" ng-model="ctrl.user.email" name="email" class="email" placeholder="Enter your Email" required />
    <span ng-show="myForm.$dirty && myForm.email.$error.required">This is a required field</span>

    <input type="submit" value="Submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js">
</script>
<script>
    angular.module('myApp', [])
    .controller('AppController', [function () {
        var self = this;
        self.submit = function () {
            console.log('Form is submitted with following user', self.user);
        };
    }]);
</script>

When angular submit a form it make $submitted property on form level to true , also it adds ng-submitted class on form 's class attribute.

You could use $submitted property of form object like myForm.$submitted to identify that form has been submitted or not

ng-show="myForm.$submitted && myForm.uname.$error.required"

Demo Plunker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM