使用Ng模型进行角度形式验证

时间:2016-10-27 19:18:21

标签: angularjs angularjs-validation angularjs-ng-form

问题:如果我无法命名表单及其元素,如何仅使用ng-model显示验证错误。

我有一个html表单来收集信用卡详细信息。为防止信用卡数据触及我的服务器,我无法命名表单元素。所以我的表格看起来像:

<form ng-submit="vm.processForm()">

  <div class="form-row">
    <label>
      <span>Card Number</span>
      <input type="text" size="20" data-stripe="number" ng-model="vm.number" required>
    </label>
  </div>

  <div class="form-row">
    <label>
      <span>Expiration (MM/YY)</span>
      <input type="text" size="2" data-stripe="exp_month" ng-model="vm.exp_month" required>
    </label>
    <span> / </span>
    <input type="text" size="2" data-stripe="exp_year" ng-model="vm.exp_year" required>
  </div>

  <div class="form-row">
    <label>
      <span>CVC</span>
      <input type="text" size="4" data-stripe="cvc" ng-model="vm.cvc" required>
    </label>
  </div>

  <input type="submit" class="submit" value="Submit Payment">
</form>

通常在Angular中,我曾经使用表单元素名称检查验证,例如:

<p ng-show="userForm.creditcard.$error.required">Your credit card number is required.</p>

但由于我无法命名表单及其元素,如何仅使用ng-model显示验证错误?因为,以下不起作用:

<p ng-show="vm.number.$error.required">Your credit card number is required.</p>

我正在使用Angular v1.4.8。

1 个答案:

答案 0 :(得分:2)

我创建了一个导出模型控制器的指令。我不认为这是最好的方式,但它有效。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="container main-content">
  <div class="row">
    <div class="col-md-6">
      Here ist the content... Here is the content... Here is the content... Here ist the content... Here is the content... Here is the content... Here ist the content... Here is the content... Here is the content... Here ist the content... Here is the content...
    </div>
    <div class="col-md-6">
      Here ist the content... Here is the content... Here is the content... Here ist the content... Here is the content... Here is the content... Here ist the content... Here is the content... Here is the content... Here ist the content... Here is the content...
    </div>
  </div>
</div>

<div class="outer">
  Outer
</div>

http://jsfiddle.net/Lvc0u55v/11352/

相关问题