0

I am trying to validate some input fields using angularJS. I found some example. But they are validating entire form.

<div ng-app="myApp" ng-controller="myCtrl">

    <form name="myform">
        <input type="text" ng-model='name' ng-required="true" />
        <input type="password" ng-model='password' ng-required="true" />
        <button ng-click="myform.$valid && preview()">Preview</button>
        <button ng-click="myform.$valid && update()">Update</button>
    </form>

</div>

and controller code is

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name=undefined;
    $scope.preview = function(){
        alert("Previewed");
    };
    $scope.update = function(){
        alert("Updated");
    }
});

The above code validating the fields based on form name. But I wanted to know is there any way to validate that particular input field ?

2
  • There are many ways, but is exactly the desired result? Commented Feb 23, 2016 at 9:29
  • With validating, you mean validating if your inputs content is for e.g. a number, a particular string, etc.? Commented Feb 23, 2016 at 9:29

2 Answers 2

2

DEMO Yes you can, you must specify a name for the input like

<div ng-app="myApp" ng-controller="myCtrl">

    <form name="myform">
        <input type="text" name='name' ng-model='name' ng-required="true" />
        <input type="password" ng-model='password' ng-required="true" />
        <button ng-click="myform.$valid && preview()">Preview</button>
        <button ng-click="myform.$valid && update()">Update</button>
    </form>

</div>

then you can check if the name is valid with myForm.name.$valid

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

Comments

0

Check out the fiddle here.

Just add a name to the input filed and follow the same as you did to the form.

HTML:

<div ng-app="myApp" ng-controller="myCtrl">

    <form name="myform">
        <input type="text" ng-model='name' ng-required="true" name="txtName" />
        <input type="password" ng-model='password' ng-required="true" />
        <button ng-click="myform.$valid && preview()">Preview</button>
        <button ng-click="myform.$valid && update()">Update</button>
        <div>Status of name: <span style="color: blue">{{myform.txtName.$valid}}</span></div>

    </form>

</div>

JS:

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
    $scope.name = undefined;
    $scope.preview = function () {
        alert("Previewed");
    };
    $scope.update = function () {
        alert("Updated");
    }
});

Comments

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.