AngularJS: Number (Age) range validation using Regular Expressions

mahesh213
 
on Apr 07, 2020 08:06 AM
1705 Views

Hi,

I have one field Age

currently my requirement in that min value should be 18 and max value should be 60

if i am trying to enter less than 18 don't allow to enter

in the same way if i am trying to enter greater than 60 don't allow

could you please help me 

<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', []);
        app.controller('MyController', function ($scope) {
           
        });
    </script>
</head>
<body ng-app="MyApp" ng-controller="MyController">     
    Number : <input type="text" ng-model="Age" /><br />    
</body>
</html>
Download FREE API for Word, Excel and PDF in ASP.Net: Download
Mudassar
 
on Apr 07, 2020 10:48 AM
on Apr 07, 2020 10:48 AM

Try this. I have created a sample which uses Regular Expression (Regex) to perform validation of Age.

 

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
        .error
        {
            color:Red;
        }
    </style>
</head>
<body>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope) {
        });
    </script>
    <div ng-app="MyApp" ng-controller="MyController">
        <form name="MyForm" ng-submit="MyForm.$valid" novalidate>
        <table border="0" cellpadding="0" cellspacing="5">
            <tr>
                <td>
                    Age:
                </td>
                <td>
                    <input type="text" ng-model="Age" name="Age" required ng-pattern="/^(?:1[8-9]|[2-5][0-9]|60)$$/" />
                </td>
                <td>
                    <span class="error" ng-show="MyForm.Age.$error.required">*Required</span> <span
                        class="error" ng-show="MyForm.Age.$error.pattern">*Invalid Age. Valid 18-60</span>
                </td>
            </tr>
            <tr>
                <td colspan="3">
                    <hr />
                </td>
            </tr>
            <tr>
                <td colspan="2" align="right">
                    <button type="submit" ng-disabled="MyForm.$invalid">Submit</button>
                </td>
            </tr>
        </table>
        </form>
    </div>
</body>
</html>

Demo