AngularJS ng-required Directive
The ng-required Directive in AngularJS is used to specify the required attribute of an HTML element. The input field in the form is required only if the expression inside the ng-required directive returns true. It is supported by <input>, <select> and <textarea> tags.
Syntax:
<element ng-required="expression">
Contents...
</element>
Example 1: This example uses the ng-required Directive to set the input text field of the form tag to required.
HTML
<!DOCTYPE html>
< html >
< head >
< title >ng-required Directive</ title >
< script src =
</ script >
< style >
.req {
font-size: 90%;
font-style: italic;
color: red;
}
</ style >
</ head >
< body style = "text-align:center" >
< h1 style = "color:green;" >
GeeksforGeeks
</ h1 >
< h3 >ng-required Directive</ h3 >
< div ng-app = "app" ng-controller = "myCtrl" >
< form name = "myForm" >
< p >Enter Your Name: < br />
< span >
< input type = "text"
name = "gfg"
ng-model = "Name"
ng-required = "true" />
</ span >
</ p >
< span ng-show = "myForm.gfg.$invalid" class = "req" >
This is the required field.
</ span >
</ form >
</ div >
< script >
var app = angular.module("app", []);
app.controller("myCtrl", function ($scope) {
$scope.Name = "";
});
</ script >
</ body >
</ html >
|
Output:
Example 2: This example uses the ng-required Directive to create the required field after checking the checkbox.
HTML
<!DOCTYPE html>
< html >
< head >
< title >ng-required Directive</ title >
< script src =
</ script >
</ head >
< body ng-app = "app" style = "text-align:center" >
< h1 style = "color:green" >
GeeksforGeeks
</ h1 >
< h2 >ng-required Directive</ h2 >
< div ng-controller = "geek" style = "font-family:arial;" >
< form name = "myform" >
< label for = "requiredValue" >
Is Required:
</ label >
< input type = "checkbox"
ng-model = "requiredValue"
id = "required" />
< br >< br >
< label for = "input" >Enter Name: </ label >
< input type = "text"
ng-model = "model"
id = "input"
name = "input"
ng-required = "requiredValue" />
< br >
< p style = "color:red;"
ng-show = 'myform.input.$error.required' >
Name is required
</ p >
</ form >
</ div >
< script >
var app = angular.module('app', [])
app.controller('geek', ['$scope', function ($scope) {
$scope.requiredValue = true;
}]);
</ script >
</ body >
</ html >
|
Output:
Last Updated :
01 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...