1

In form I have controls with name,id and class attribute. I cant add any costom attribute in html input element. In this case how can I apply validation.

Can I write directive on element name or id?

HTML

<form class="form-horizontal text-center" role="form" name="DTOstep1" ng-submit="onSubmit(DTOstep1)" novalidate>
<input name="userinput1" id="userinput1" class="" />
<input name="userinput2" id="userinput2" class="" />
<input name="saveDto" type="submit" class="btn btn-success btn-lg" value="Continue" />
</form>

directive code

(function () {
    "use strict";

    angular
            .module("autoQuote")
            .directive('userinput1', [userinput1])
            ....

Or is there any other way to do form validation. I wan to apply some custom validation to each form field.

3 Answers 3

1

The angular way requires the ng-model attribute to each field, in order to bind it with a model property.

function TestCtrl($scope) {
  $scope.fields = {
    "userinput1" : "Initial Value",
    "userinput2" : ""
  }
  
  $scope.onSubmit = function onFormSubmit($event, form) {
    if(form.$invalid) {
      console.log("invalid", form);
      event.preventDefault();
      return;
    }
    
    console.log('valid', form);
    //send here
  };
}
angular
  .module('test', [])
  .controller("TestCtrl", ["$scope", TestCtrl])
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
  <article ng-controller="TestCtrl">
    <form name="DTOstep1" ng-submit="onSubmit($event, DTOstep1)">
      
      <input name="userinput1" ng-model="fields.userinput1" required/>
      <input name="userinput2" ng-model="fields.userinput2" required />
      
      <input name="saveDto" type="submit" ng-disabled="DTOstep1.$pristine || DTOstep1.$invalid" />
</form>
  </article>
</section>


by the way, if you can't edit the view in order to create an angular-form, you need to control the form via dom queries, such as vanilla javascript... using document.querySelector() and checking value property.


UPDATE

Many basic check could be made using simple procedural approach, if you want apply a minlength to the userinput1 field, on each onSubmit you need to check $scope.fields.userinput1.length > ..., et cetera...

A more clean and suggested way is to use html5 validation attributes, angular decorates them and recognize thei rules, so, you can use min/max/min-length/max-length/required/pattern/disabled etc.

if you want to provide a reusable way, you should have a look at FormController.$addControl or how build a custom directive via attributes that requires ngModelController and so on...

Sign up to request clarification or add additional context in comments.

7 Comments

using TestCtrl an ng-model is helpfull. how can I apply validation on input here?
Can I make rules that I can apply to fields, so that we could reuse rules for multiple filed if required.
If I make attribute like myInput="userinput1" and for next myInput="userinput2". then can I apply validation on myInput attribute value.
<input myInput="userinput1" name="userinput1" ng-model="fields.userinput1" required/>
the myInput attribute doesn't exist... what do you mean with it? A custom Directive? For doing what?
|
0

Add required to those fields on which you want to add validation -

'use strict';
 var app = angular.module("demo", [], function($httpProvider) {

});

app.controller("demoCtrl", function($scope) {
    $scope.onSubmit = function(){
      alert('form valid');
      }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="demo">
<div ng-controller="demoCtrl">
<form name="form" id="form" class="form-horizontal text-center" role="form" >
<input ng-required="true" ng-model="userinput1" name="userinput1" id="userinput1" class="" /><br>
Check it to make userinput 2 required:  <input type="checkbox" ng-model="check" />
<input  ng-required="check" ng-model="userinput2" name="userinput2" id="userinput2" class="" />
<br><input ng-click="onSubmit(DTOstep1)" ng-disabled="form.$invalid" name="saveDto" type="submit" class="btn btn-success btn-lg" value="Continue" /><br>
</form>
  </div>
</body>

you can also use ng-model inside ng-required to toggle the ng-required true and false.

5 Comments

require is there with all fields. i want to apply some custom validations.
I didn't understand your answer. Can you please explain?
what kind of custom validation you want?
something like check value in a set. or validate from server call(Ajax)
i have added checkbox validation just for demo purpose it can be as complex as you want and for server validation you have to do it in controller onsubmit function
0

angular automatically adds classed to each ng-model

This should help https://docs.angularjs.org/guide/forms

Adding a fiddle as an example

https://jsfiddle.net/x0f6czfk/

<body ng-app="app">
  <form ng-controller="mainCtrl">
    <input ng-model="name" type="text">
    <input ng-model="email" type="text">
    <input type="button" ng-click="validateForm()" value="Save">
  </form>
</body>

(function(window,document,undefined){
var app = angular.module('app',[]);


  app.controller('mainCtrl',function($scope){
    var self = this;
    $scope.validateForm = function(){
    //custom validation
        if($scope.name === 'test'){
        console.log('wrong name');
        return;
      }
     //custom validation
     if($scope.email === '[email protected]'){
                console.log('wrong email');
          return;
        }
      else{
      //if no validation error, submit data;
        console.log('valid form');
      }
    }
  });
})(window,document)

1 Comment

Yes, but those classes are same for all controls. How to distinguish each field. Like I want to apply validation form userinput1 only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.