Activity Forums Salesforce® Discussions How to Validate string that is Numeric in AngularJs ?

  • Piyush

    Member
    January 11, 2018 at 7:00 am

    I have created a input text field in AngularJs. And my requirement is that user only able to enter Numeric value. If user try to enter any character or Special character then it not allow to enter .
    Any help will really appreciable.

  • Adarsh

    Member
    January 11, 2018 at 7:58 am

    Hello Piyush,

    If we talking about only this requirement, then I think this is the simplest and fastest way for allowing the Number input only.

    <input type="text" id="NumOlny" placeholder="Enter a Number" onkeypress='return event.charCode >= 48 && event.charCode <= 57' required>

    Hope it helps 🙂

  • Piyush

    Member
    January 11, 2018 at 8:16 am

    Hi Adarsh,

    Thanks for the response but I need this functionality in AngularJS. In AngularJs we did not support "return event.charCode".

     

  • Adarsh

    Member
    January 11, 2018 at 10:22 am

    Hi,

    You may use “return event.keyCode“ or there is a script, may it helps you.

    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script>
    var app = angular.module('app', []);
    app.directive('numbersOnly', function () {
    return {
    require: 'ngModel',
    link: function (scope, element, attr, ngModelCtrl) {
    function fromUser(text) {
    if (text) {
    var transformedInput = text.replace(/[^0-9]/g, '');

    if (transformedInput !== text) {
    ngModelCtrl.$setViewValue(transformedInput);
    ngModelCtrl.$render();
    }
    return transformedInput;
    }
    return undefined;
    }
    ngModelCtrl.$parsers.push(fromUser);
    }
    };
    });
    </script>
    <div ng-app="app" class="container">
    <p><input type="text" ng-model="val" numbers-only class="form-control" /></p>
    </div>
    </html>

     

Viewing 1 - 4 of 4 posts

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos