Neel Neel - 1 month ago 17
AngularJS Question

Angular Form Validation using Ng Model

Question: How can I show the validation error using only the

ng-model
if I cannot name the form and its elements.

I have a html form to collect credit card details. To prevent the credit card data from touching my server, I cannot name the form elements. So my form looks like:

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


Usually in Angular, I used to check validation using the form elements name, for example like this:

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


But since I cannot name the form and its elements, how can I show the validation error using only the ng-model? Because, the following doesn't work:

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


I am using Angular v1.4.8.

Answer

I created a directive to export de the model controller. I don't think that is the best way but it works.

.directive('exportModel', function () {
    return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, element, attr, ngModel) {
        attr.$observe('exportModel', function (value) {
        scope[value] = ngModel;
      })
    }
  }
})

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