簡體   English   中英

在Angularjs中提交表單時顯示驗證消息

[英]Display validation message on submitting the form in Angularjs

我想在用戶單擊提交表單后顯示驗證消息。 例如,文本框是必填項,用戶直接單擊提交按鈕,則將顯示驗證字段。

在這里,當用戶單擊表單時,沒有任何反應。

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

當angular提交一個表單時,它使表單級別的$submitted屬性為true ,並且還在form的class屬性上添加了ng-submitted類。

您可以使用像myForm.$submitted這樣的表單對象的$submitted屬性來標識該表單是否已提交

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

演示柱塞

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM