Tzof
Tzof

Reputation: 191

Getting the field of form angular

I have a form with some fields.
I'm validating the fields with css classes:(if the field is invalid and the user touched it, then input's border-color = red.)

select.ng-invalid.ng-touched,
input.ng-invalid.ng-touched,textarea.ng-invalid.ng-touched {
    border-color: red;
}

If the user submits the form without filling one or more field, there would be a danger alert.

HTML:

  <div ng-show="formInvalid>
       error!
  </div>

JS:

 if ($scope.pniyaForm.$valid) {
    $scope.formInvalid = false;
      .....
 } else {
    $scope.formInvalid = true;
 }

But, If the user submits the form and has not touched any of the field, the css classes don't influence.(because user didn't touch...)
I want to add the class in the code.
Does anyone have an idea for an elegant way to do this without writing it on each field separately?

Upvotes: 5

Views: 94

Answers (3)

chinna bs
chinna bs

Reputation: 11

Using ng-class validation in angularjs

<div class="form-group">
    <label>Name</label>
    <input type="text" required ng-model="name" name="name" ng-class="{'has-error': myForm.name.$invalid}" />
</div>

<div class="form-group">
    <label>Age</label>
    <input type="text" required ng-model="age" name="age" ng-class="{'has-error': myForm.age.$invalid}" />
</div>

Upvotes: 1

svarog
svarog

Reputation: 9847

If the user submits the form and has not touched any of the field, the css classes don't influence

You need to provide an initial defined value to an ngModel and at least provide the required attribute to an input.

Use ngClass to conditionally apply css classes in case some form parts are invalid

<form name="myform">
    <div class="form-group" ng-class="{'has-error': myform.myinput.$invalid}">
        <input name="myinput" ng-model="myName" class="...." required> 
    </div>
....
</form>

....
// in controller
$scope.myName = "cats"; // form is valid
$scope.myName = "";     // form is invalid, and the css class 'has-error' will be applied 

Then use ngDisables in your submit button to prevent submission in case the form is invalid

<button type="submit" ng-disabled="myform.$invalid">submit</button>

Upvotes: 0

Arel Sapir
Arel Sapir

Reputation: 136

A possible solution:

when you are executing your form function, add the following line into it.

$scope.$apply(function () {});

this line will cause the ng $scope.$watch() run and apply changes if they exist. may work, may not work, read the following link for deeper understanding of the issue.

http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

Upvotes: 1

Related Questions