【问题标题】:AngularJS form with validation带有验证的 AngularJS 表单
【发布时间】:2026-01-08 00:00:01
【问题描述】:

我创建了一个包含六个字段的表单,其中五个是必填字段。有一个提交按钮。如果用户没有在文本框中输入任何内容并单击提交按钮,则所有必需的文本框都应以红色边框突出显示。如何实施? :-

<div ng-app="myApp" ng-controller="formCtrl">
        <form name="demoForm">
            <label>First Name :</label>
            <input type="text" ng-model="firstName" required/><br><br>
            <label>Last Name :</label>
            <input type="text" ng-model="lastName"/><br><br>
            <label>Email :</label>
            <input type="email" ng-model="emailDet" required/><br><br>
            <label>Contact No :</label>
            <input type="text" ng-model="contactNo" required/><br><br>
            <label>Current Location :</label>
            <input type="text" ng-model="currLoc" required/><br><br>
            <label>Preferred Location :</label>
            <input type="text" ng-model="preLoc" required/><br><br>
            <button type="button" ng-click="onSubmit()">Submit</button>
        </form>
    </div>
    <script>
        var app = angular.module('myApp', []);
        app.controller('formCtrl', function($scope) {
            $scope.onSubmit = function() {

            }
        });
    </script>

【问题讨论】:

标签: angularjs


【解决方案1】:

这很容易。像这里定义新的 css 规则,一切都应该没问题

.ng-invalid.ng-submitted input {
     border: 1px solid red;
}

在后台,Angular 为您的表单和输入分配了许多类。

.ng-无效

表示表单上有问题

.ng-提交

表示表单已提交。

等等。查看文档,您会发现很多新发现。

【讨论】: