This code sample are used to validate a required field with single word which are given below.
Table of Contents.
<!doctype html>
Table of Contents.
- input type is equal to text [type="text"].
- ng-pattern with single word.
- Required element tag.
- ng-model with two way binding.
<!doctype html>
<html>
<head>
<title> angularjs requiredvalidation </title>
<script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
<style>
.error {
color: red;
}
</style>
<script>
var app = angular.module('myApp', []);
app.controller('mainCtrl', function ($scope) {
$scope.username = '';
$scope.singleword = /^\s*\w*\s*$/;
});
</script>
</head>
<body ng-app="myApp">
<ng-form name="myForm" ng-controller="mainCtrl">
<div>UserName :</div>
<div>
<input type="text" name="name" ng-model="username" ng-pattern="singleword" required>
<span class="error" ng-show="myForm.name.$error.required">Required!</span>
<span class="error" ng-show="myForm.name.$error.pattern">Only single word.</span>
</div>
</ng-form>
</body>
</html>
The result look like below image.