AngularJS input masking

I am trying to implement a mask for an input field where users can only input symbols following a specific template: "01ABC2345-67-89" - two digits, followed by three characters, then four digits, a "-", two more digits, another "-" and finally, two more digits. Currently, my code only filters out numbers. How can I create a regular expression to achieve this objective?

Here is the HTML:

<html ng-app="app">
    <head>
        <meta charset="UTF-8">
        <title>serialNumber mask</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
        <script type="text/javascript" src="main.js"></script>
    </head>
    <body ng-controller="myCtrl">
        <input type="text" id="serialNumber" ng-model="model.serialNumber">
        <br>
        <label for="serialNumber">format: 01ABC2345-67-89</label>
        <br><br>
{{model.serialNumber}}
    </body>
</html>

and here is the JavaScript:

var app = angular.module('app', []);

app.controller('myCtrl', function ($scope) {
    $scope.model = {};
    $scope.$watch('model.serialNumber', function (newValue, oldValue) {
        console.log('newValue', newValue);
        var regex = new RegExp('^\\d+$');
        if (newValue) {
            if (!regex.test(newValue)) {
                $scope.model.serialNumber = oldValue;
            }
        }

    });
});

Answer №1

Take a look at this example. The only issue is that it doesn't delete properly. I'm confident you can tackle this problem on your own.

The Regex pattern used matches any digit [0-9] twice, followed by any character [A-Z] three times, then another set of any number [0-9] four times, a hyphen "-", two more digits [0-9], another hyphen "-", and finally two more digits [0-9]. The "^" symbol indicates the sequence starts with, while the "$" symbol denotes the end. In essence, it targets any line that begins and ends with that particular Regex pattern.

^[0-9]{2}[A-Z]{3}[0-9]{4}-[0-9]{2}-[0-9]{2}$

var app = angular.module('app', []);

app.controller('myCtrl', function($scope) {
  $scope.model = {};

  $scope.checkForChanges = function() {
    var regex = new RegExp('^[0-9]{2}[A-Z]{3}[0-9]{4}-[0-9]{2}-[0-9]{2}$');
    var len = $scope.model.serialNumber.length;
    if (len == 9 | len == 12) {
      $scope.model.serialNumber += "-";
    }
    if (regex.test($scope.model.serialNumber)) {
      console.log("matches");
      $scope.isMatch = "Regex match!";
    } else {
      $scope.isMatch = "Regex mismatch!";
    }

  }

  $scope.clear = function() {
    $scope.model.serialNumber = "";
  }
});
<html ng-app="app">

<head>
  <meta charset="UTF-8">
  <title>serialNumber mask</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>

<body ng-controller="myCtrl"> <input type="text" id="serialNumber" ng-model="model.serialNumber" ng-change="checkForChanges()"> <br> <label for="serialNumber">format: 01ABC2345-67-89</label> <br>
  <button ng-click="clear()">Clear</button>
  <br> {{model.serialNumber}} </body>
<div>{{isMatch}}</div>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Node.js, express, jade, highcharts, and a 2D array

Greetings, I am relatively new to the realm of javascript/node.js/express/jade/highcharts etc... The predicament at hand is as follows: I have a template that takes in a few parameters which are pre-processed in my router code. These parameters are group ...

How can I clear all jQuery toggled classes that have been added across the entire webpage in an Angular project?

Upon clicking a link within an element, the following CSS is applied: <a class="vehicleinfo avai-vehicle-info-anc-tag" ng-click="vehicleInfo($event)">Vehicle Info <span class="s-icon red-down-arrow"> </span> </a> $scope.vehic ...

trouble encountered when attempting to integrate typeahead functionality in AngularJS using jQuery

Greetings! I am brand new to using AngularJS and currently exploring the implementation of typeahead functionality. I decided to utilize an existing library by including the following script: <script src="lib/xyz/typeahead.bundle.js"></script> ...

Error: Attempting to access property 'email' from an undefined object was unsuccessful

I'm currently working on a Vue.js app with Laravel but I'm having trouble accessing the component from the object. What steps should I take? <script> import axios from 'axios'; export default { data : function (){ ret ...

JavaScript can retrieve the default page name that is hidden within the browser's URL

When a URL is entered without a specific file name at the end, such as "www.google.com," the server typically serves a default file like "index.html" or "default.aspx." In this scenario, if the browser displays "www.google.com," I am looking to extract the ...

The functionality of the Array.sort method is known to cease functioning when the length of the Array exceeds

I have been working on a hybrid application that combines Angular and Ionic's framework. Recently, I discovered an issue with one of my functions not functioning as expected. Within my app, users are able to create a database of items stored as objec ...

Create a full duplication of every field and array within an object using AngularJs with the deepCopy method

I am looking to replicate certain fields within an object in other fields of the same object, similar to the concept demonstrated below: var customers = { apple: { papa: { en: "cool" } }, oranges: { papa: { ...

Error: undefined property causing inability to convert to lowercase

I am encountering an error that seems to be stemming from the jQuery framework. When I attempt to load a select list on document ready, I keep getting this error without being able to identify the root cause. Interestingly, it works perfectly fine for the ...

Tools needed for Angular project development

Currently, I am engaged in a project using AngularJS on a Windows 7 computer. My desire is to be able to seamlessly transition between working at the office and working from home or any other location. If I have everything installed in a folder named C:/C ...

What is the best way to display images when a single element in a list created by ngFor is hovered over in Angular 2

displayStar(val) { this.starDisplayed = true; } <ul class="listboxtickets"> <li class="selectlistticket" *ngFor="let item of ticketList" (mouseover)="displayStar(item.id)" (mouseleave)="hideStars()"> <div class="ticket ...

Creating a sticky header for a MatTable in Angular with horizontal scrolling

Having an issue with merging Sticky Column and horizontal scrolling. Check out this example (it's in Angular 8 but I'm using Angular 10). Link to Example The base example has sticky headers, so when you scroll the entire page, the headers stay ...

Invoking RESTful services using parameters

Currently, I am tackling a project that involves coding in both Java and Angular. The request is sent from Angular with specified parameters, which I need to retrieve in the REST services on the Java side. While I am unable to alter the Angular component, ...

Understanding how the context of an Angular2 component interacts within a jQuery timepicker method

Scenario: I am developing a time picker component for Angular 2. I need to pass values from Angular 2 Components to the jQuery timepicker in order to set parameters like minTime and maxTime. Below is the code snippet: export class TimePicker{ @Input() ...

Error code EPERM encountered while attempting to append a file on a network

An issue arises when the application is required to store log data on a network drive. While everything works smoothly when the drive is hosted under Windows, complications arise when it is hosted on a Mac. Read/write operations function properly, but appe ...

Unexpected behavior with ng-show binding

I am currently working on implementing a toggle feature in my form. The idea is that when I click one button, it should display a section with the corresponding name, and hide the other sections. However, I am facing an issue related to scope. When I do no ...

Setting up numerous instances of TinyMCE for use

I am having trouble initializing two instances of tinymce on my webpage. Even after following the guidance provided in this particular thread, I am unable to get it working. Could it be possible that I need to introduce a timeout between initializing the ...

Using Angular to dynamically access component properties

Seeking assistance with creating dynamic Tabs in TabView of PrimeNG. The components are displaying properly, but I am unsure how to access their properties. I am following the guidelines provided at https://angular.io/guide/dynamic-component-loader and us ...

Retrieve the image object by its path on a mobile device using Ionic, Cordova, and Angular

Currently working on a mobile app utilizing Ionic, Cordova, and Angular. I am facing a challenge in retrieving an image file by its path to send it to the server. For reference, I am following this example () to capture and store images in the app folder. ...

Property list is incomplete and requires an "after" parameter

This particular piece of code is generating the following error message: missing : after property list exactly where the error comment is placed. $("#jquery_jplayer_1-<?php echo $key.'-'.$j; ?>").jPlayer({ ready: function () { ...

Updating website content dynamically using Javascript and JSON-encoded data

My programming code seems to be acting oddly. I have structured my data in a JSON object as follows: injectJson = { "title": "Champion Challenge Questions", "rules": [ { "idChrono": "chrono-minute", "text": "Top is missing!", ...