AngularJS技术问题:输入长度超限如何禁用提交按钮
解决AngularJS输入框长度超限但表单仍显示valid的问题
嘿,我明白你遇到的问题了——你手动给输入框添加了ng-invalid/ng-valid类,但Angular的表单验证系统根本不吃这一套😅。Angular的表单和控件状态(比如paramForm.$invalid)是由它自身的验证机制管理的,手动添加CSS类不会触发这些状态的更新,所以即使你把输入框标红了,表单还是觉得它是有效的。
问题根源
你现在是通过ng-class手动给输入框贴验证类,但Angular只认自己通过验证指令(比如ng-required、ng-maxlength)生成的状态。你的paramForm.$invalid依赖的是控件的$valid/$invalid属性,而这些属性不会因为你手动加CSS类而改变。
正确解决方案
我们可以用Angular原生的ng-maxlength指令,绑定每个输入框对应的p.MaxLength值,让Angular自动处理验证状态。同时调整你的字符剩余数计算逻辑,避免空值报错:
修改后的HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"> <script src="../lib/angular.min.js"></script> <style type="text/css"> ol { margin: 20px 0; padding: 20px; } input.ng-dirty.ng-invalid { border: 1px solid red } </style> </head> <body ng-app="ngrepeatApp" ng-controller="ngrepeatCtrl"> <div class="container"> <form novalidate name="paramForm"> <div class="form-group" ng-repeat="p in params"> <label>{{p.Title}}</label> <!-- 用ng-maxlength绑定动态最大值,移除手动的ng-class --> <input type="text" class="form-control" placeholder="{{p.Description}}" required ng-model="p.Value" ng-maxlength="{{p.MaxLength}}"> <small class="form-text text-muted">Available <span>{{lengthDifference(p)}}</span> symbols</small> </div> <button type="submit" class="btn btn-success" ng-disabled="paramForm.$invalid">Submit</button> </form> </div> <script src="app.js"></script> </body> </html>
修改后的控制器代码
var app = angular.module("ngrepeatApp", []); app.controller("ngrepeatCtrl", function ($scope) { $scope.lengthDifference=function(p){ // 处理Value为空的情况,避免undefined.length报错 var currentLength = p.Value ? p.Value.length : 0; var left = p.MaxLength - currentLength ; return left; }; $scope.params = [ { Title: "Title", Description: "Type Title Here", Value: "", MaxLength: 10 }, { Title: "DisplayName", Description: "Type Title Here", Value: "", MaxLength: 15 }, { Title: "Category", Description: "Type Category Here", Value: "", MaxLength: 6 } ]; });
为什么这样可行?
ng-maxlength="{{p.MaxLength}}"会让Angular自动监听输入框的字符长度,当超过p.MaxLength时,会给输入框添加ng-invalid-maxlength类,同时把该控件的$invalid状态设为true。- 结合你原本的
required指令,只要输入框为空或者长度超限,控件都会处于无效状态,进而让整个paramForm.$invalid变为true,自动禁用提交按钮。 - 你原来的红色边框样式
input.ng-dirty.ng-invalid依然有效,因为Angular会自动添加这些状态类。
这样修改后,表单的验证状态就会和输入框的实际情况同步,字符剩余数显示也正常,提交按钮会在任何输入框无效时被禁用啦。
内容的提问来源于stack exchange,提问作者Dmitriy Pashko
相关产品推荐
相关产品推荐

