Am trying to validate an Email id field in angularJs using ng-pattern directive.
But am new to AngularJs. I need to show an error message as soon as the user enters the wrong email id.
The code which I have below is am trying to solve. Help me out with using ng-pattern for getting the proper result.
<script type="text/javascript" src="/Login/script/ang.js"></script>
<script type="text/javascript">
function Ctrl($scope) {
$scope.text = 'enter email';
$scope.word = /^[a-z]+[a-z0-9._]+@[a-z]+\.[a-z.]{2,5}$/;
}
</script>
</head>
<body>
<form name="myform" ng-controller="Ctrl">
<input type="text" ng-pattern="word" name="email">
<span class="error" ng-show="myform.email.$error.pattern">
invalid email!
</span>
<input type="submit" value="submit">
</form>
</body>
Below is the fully qualified pattern for email validation.
This is jQuery Email Validation using Regex Expression. you can also use the same concept for AngularJS if you have idea of AngularJS.
Source.
angularjs controller way, just an example to look for one or more email in the body of a message.
Now, Angular 4 has email validator built-in https://github.com/angular/angular/blob/master/CHANGELOG.md#features-6 https://github.com/angular/angular/pull/13709
Just add email to the tag. For example
You can use ng-messages
include the module
in html
If you want to validate email then use input with type="email" instead of type="text". AngularJS has email validation out of the box, so no need to use ng-pattern for this.
Here is the example from original documentation:
For more details read this doc: https://docs.angularjs.org/api/ng/input/input%5Bemail%5D
Live example: http://plnkr.co/edit/T2X02OhKSLBHskdS2uIM?p=info
UPD:
If you are not satisfied with built-in email validator and you want to use your custom RegExp pattern validation then ng-pattern directive can be applied and according to the documentation the error message can be displayed like this:
Plunker: https://plnkr.co/edit/e4imaxX6rTF6jfWbp7mQ?p=preview