繁体   English   中英

带有ng-pattern形式的AngularJS不会将无效字段发送到服务器

[英]AngularJS with ng-pattern in form does not send invalid field to server

我想验证表单中的文本输入,因此在输入匹配正则表达式之前无法完成表单的提交。 但是,当我键入了错误的字段值并且单击提交时,将提交表单,但输入值不会发送到服务器。 我想要与HTML5必需属性相同的行为。 这是我的代码:

<div class="row">
    <label class="col-sm-2 label-on-left">APN</label>
    <div class="col-sm-7">
        <div class="form-group label-floating">
            <label class="control-label"></label>
            <input class="form-control" type="text" name="apn" ng-model="Configure3gCtrl.configure3g.apn" ng-pattern="/^[a-zA-Z0-9-.]*$/" required/>
        </div>
    </div>
</div>          

正如我在评论中所说的那样 [未发送值,因为当您以错误的模式传递输入时ng-modelundefined ]。

但是,如果我们的ng-model invalid ,则可以在此处使用表单验证作为示例,表单将被禁用。

 var app = angular.module("app", []); app.controller("ctrl", ["$scope", "$filter", function($scope, $filter) { $scope.submit = function() { console.log($scope.object) } }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="ctrl"> <form name="form"> <label class="col-sm-2 label-on-left">APN</label> <input type="text" name="apn" ng-model="object.apn" ng-pattern="/^[a-zA-Z0-9-.]*$/" required /> <button ng-click="submit()" ng-disabled="form.$invalid">submit</button> </form> </div> 

理想情况下,您不应该将无效值发送到服务器,因此应该disable\\hide提交按钮,但是如果您确实需要将无效值也发送到服务器,那么从angularjs 1.3+开始,您可以使用ng-model-options阅读Doc )指令可以为您提供帮助。

只需将您的text type输入标记为ng-model-options="{allowInvalid: true }" ,它将同样保留无效值。

观看演示:

 var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', function MyCtrl($scope) { $scope.submitt = function() { alert($scope.Configure3gCtrl.configure3g.apn); } $scope.Configure3gCtrl = { configure3g: { apn: "" } } }); 
 <script src="https://code.angularjs.org/1.3.1/angular.js"></script> <div ng-app="myApp" ng-controller="MyCtrl"> <form name="frm" ng-submit="submitt()" class="row"> <label class="col-sm-2 label-on-left">APN</label> <div class="col-sm-7"> <div class="form-group label-floating"> <label class="control-label"></label> <input class="form-control" type="text" name="apn" ng-model="Configure3gCtrl.configure3g.apn" ng-model-options="{allowInvalid: true }" ng-pattern="/^[a-zA-Z0-9-.]*$/" required/> </div> </div> <input type="submit" value="submit" type="submit" /> </form> </div> 

同样,从上面的代码片段中删除ng-model-options="{allowInvalid: '$inherit' }" ,然后进行测试,则ng-model将是undefined ,因为它是无效的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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