angularJS:验证模式应该允许?但不应该保存到服务器

时间:2014-05-06 06:28:16

标签: regex html5 angularjs validation

Plz检查示例我需要显示“??”最初进入文本框。

但那些“??”不应该保存到服务器意味着它应该保存由regEx验证的数据。

为此我分配“??”最初它的验证然而

“??”没有显示到文本框。

那么解决这个问题的方法是什么?

下面是HTML

<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="text" ng-model="price" name="price_field" ng-pattern="/^[0-9]{1,7}$/" required>
<span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
<input type="submit" value="submit"/></form></div>

以下是Javascript

function formCtrl($scope){
$scope.price= "??";
$scope.onSubmit = function(){
    alert("form submitted");
}}

检查JsFiddle sample

-Thanks,

约杰什

3 个答案:

答案 0 :(得分:1)

似乎输入在与正则表达式匹配之前不会显示

所以试试这个,

Html文件,

<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit(price)">
    <input type="text" ng-model="price" required  />
   <span ng-hide="validater">Not a valid number!</span><br>
    <input type="submit" value="submit"/>
</form>
</div>

Js文件,

function formCtrl($scope){
    $scope.price= "??";
       $scope.onSubmit = function(price){
       $scope.validater= new RegExp("^\[0-9]{1,7}$").test(price);

        //alert("validater "+ $scope.validater);

        if(!$scope.validater){
              $scope.price= "??";
        }else{
           alert("form submitted");

        }

        return  $scope.validater;       

    }
}

希望这能解决您的问题:)

以下是工作演示jsfiddle

答案 1 :(得分:0)

尝试使用这样的。

<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()"> 

<input type="text" ng-model="price" name="price_field" placeholder="Enter a number" ng-pattern="/^[0-9]{1,7}$/" required>

<span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>

<input type="submit" ng-disabled="myForm.$invalid" value="submit"/></form></div>

在你的JS中

function formCtrl($scope){
$scope.price= "-1";
$scope.onSubmit = function(){
    alert("form submitted");
}}

答案 2 :(得分:0)

看看这个。

<强> Working Demo

enter image description here

<强> HTML

<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
    <input type="text" ng-model="price" name="price_field" ng-pattern="/^[0-9]{1,7}$/" placeholder="??" required >
    <span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
    <input type="submit" value="submit"/>
</form>
</div>

<强>脚本

function formCtrl($scope){
    $scope.price= "";
    $scope.onSubmit = function(){
        alert("form submitted");
    }
}