Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-show with regex using angular js

I have two images , based on input regex pattern i want to display one image at a time.

My code is

<input type="password" ng-model="password" placeholder="Enter Password"/>

<img src="../close.png" ng-show="password != [a-z]"/>
<img src="../right.png" ng-show="password == [a-z]"/>

What will be solution for this kind of feature.

like image 315
user3864129 Avatar asked Dec 18 '25 00:12

user3864129


2 Answers

$scope.checkPassword = checkPassword;
function checkPassword(input){
	var onlySmallLetters = /^[a-z]+$/
	return onlySmallLetters.test(input);
}
<input type="password" ng-model="password" placeholder="Enter Password"/>
<img src="../close.png" ng-if="checkPassword(password)"/>
<img src="../right.png" ng-if="!checkPassword(password)"/>

checkPassword method will return false if the input contains any characters other than alphabets so close.png is only shown if the password has only alphabets otherwise right.png is shown

like image 118
ArunBabuVijayanath Avatar answered Dec 20 '25 19:12

ArunBabuVijayanath


I guess below is what you need.

Ideally input elements should be validated based on pattern and with the pattern result we will show the corresponding message to user.

So instead of checking in img tags I would prefer to check the input itself with ng-pattern and based on the validity of input I am showing the corresponding img.

See the implementation

angular.module('myApp', []);
angular.module('myApp').controller('MyController', MyController);

function MyController($scope) {

};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyController">
  <form name="form">
    <input type="password" ng-model="password" placeholder="Enter Password" ng-pattern="/^[a-z]*$/" name="password" />
    <br>
    <img src="../close.png" ng-show="form.password.$invalid && form.password.$dirty" alt="error"/>
    <img src="../right.png" ng-show="form.password.$valid && form.password.$dirty" alt="success" />
  </form>
</div>
like image 43
Gangadhar JANNU Avatar answered Dec 20 '25 21:12

Gangadhar JANNU