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