What steps can be taken to avoid special characters in ion-input fields?

When inputting special characters into the field used for storing the alphanumeric serial number, they are accepted. I need to prevent special characters from being entered in the input field.

<ion-input [(ngModel)]="serial_number" (ngModelChange)="validation($event)" #serialno  id="serialno"  class="cac-input"></ion-input>
  validation(event) {
    const inputElement = document.getElementById('serialno') as HTMLInputElement;
    const pattern = /^[a-zA-Z0-9]*$/;
    console.log(event)
    console.log(pattern.test(event))
    let c = event.replace(/[^a-zA-Z0-9 ]/g, '');
    inputElement.value = '';
    inputElement.value = c;
    console.log(c)
    this.serial_number = c;
  }

In the past, I used regex to remove the special characters, but even after removal, the value still shows up in the input field.

Using the (keypress) event in the browser works fine, however, it does not work on Android.

The field displays properly in the app

Console logging the ngmodel field shows the correct values

Answer №1

A custom validator can be implemented for this particular task: it accepts a regex input to check for valid and invalid characters, replaces any unwanted characters with an empty string, and handles paste events by cleaning out invalid characters. This functionality can all be achieved using the @HostListener attribute on events like keydown and paste!

This code snippet demonstrates how to create a directive:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[appPattern]',
})
export class PatternDirective {
  @Input() appPattern: string = '[A-Za-z0-9]';

  @HostListener('keyup', ['$event']) public onKeydown(event: any) {
    const value: string = event.target.value;
    if (!value) {
      return true;
    }
    const regExpr = new RegExp(`^(${this.appPattern})+$`);
    if (!regExpr.test(value)) {
      event.target.value = value.replace(
        new RegExp(`(${this.appPattern})|.*`, 'gm'),
        '$1'
      );
      event.preventDefault();
      return false;
    }
  }

  @HostListener('paste', ['$event']) public onPaste(event: any) {
    event.preventDefault();
    let clipboardText = event.clipboardData.getData('text');
    event.target.value = clipboardText.replace(
      new RegExp(`(${this.appPattern})|.*`, 'gm'),
      '$1'
    );
  }
  constructor(private elementRef: ElementRef) {}
}

Below is an example of how to use this directive in HTML:

<ion-input
    type="text"
    [(ngModel)]="todo.title1"
    name="title1"
    appPattern="[A-Za-z0-9]"
  ></ion-input>

Check out a live demo on StackBlitz here.

Answer №2

For a convenient one-liner solution, Ionic offers the ability to use the supported pattern attribute on ion-input:

<ion-input type="text" pattern="^[a-zA-Z0-9]*$" ></ion-input>

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

Is there a way to set a default value for the map function?

Currently utilizing React.js with the following code snippet: myArray.map(variable=>({value: variable.value, label: variable.label})) It's working well for the most part, but occasionally encountering this issue: TypeError : myArray is null Any s ...

"Troubleshooting: Next.js useEffect and useState hooks fail to function properly in a

Working on my project in nextjs, I've implemented the useEffect and useState hooks to fetch data: export default function PricingBlock({ data }) { const [pricingItems, setPricingItems] = useState() const [featuredItem, setFeaturedItem] = useState( ...

Filtering data in TypeScript from a different component with the filter function

Currently, I am in the process of creating a filter function for a table. The table header and table body are separate components - with one responsible for filtering the data and the other for displaying it. User input is stored in the Table Header Compo ...

Extract the href value from an element and append it to the src attribute of an image

How can I extract the href link from the .image1 div class? <div class="image1"> <a href="/images/productA.jpg"> </a> </div> Then, how do I insert it into the image src shown below? <ul class="example"> <li class ...

Choose or deselect images from a selection

I am currently working on a feature for an album creation tool where users can select photos from a pool of images and assign them to a specific folder. However, I'm facing difficulty in selecting individual photos and applying customized attributes t ...

The efficiency of Testing Library findBy* queries is optimized when utilized alongside async/await functionality

After reviewing the documentation, it was noted that queries made using findBy return a Promise. Interestingly, utilizing these queries with Promise.prototype.catch() seems ineffective in comparison to pairing them with async/await + try...catch. An insta ...

Issues with displaying validations on an Angular form running Angular 13 are currently being experienced

The warning message is not showing up for the radio button after submitting the form. However, if I click reset once and then submit the form, the warning appears. Please take a look at this video. Additionally, I am facing difficulties in enforcing minimu ...

Swapping a value within an array and moving it to a new position

Consider this scenario: I am dealing with a list of arrays containing values like: let data = [ "10-45-23:45", "10-45-22:45", "10-45-20:45", "10-45-23:45", "10-45-23:59,00:00-04:59", "10-45-23:59, 0 ...

Using SASS variables in JavaScript: A guide

My JavaScript file contains a list of color variables as an Object. export const colors = [ { colorVariable: "$ui-background" }, { colorVariable: "$ui-01" }, { colorVariable: "$ui-02" }, ... ] The Object above is derived from a scss file whic ...

Model with no collection involved

Take a look at this Model and View setup. Why is the indicated line not functioning as expected? var app = app || {}; (function () { app.CurrentUserView = Backbone.View.extend({ el: $('.avatar-container'), template: ux.templ ...

What is the method for storing a JSON object path in a variable for use in a template?

Trying to fetch data from a lengthy path has proven challenging for me. I attempted to store the path in a variable and incorporate it into the template, but encountered some issues. Could someone assist me with this? Here is what I have tried: My store ...

Can the individual headers of an ag-grid column be accessed in order to apply an on-mouseover event with a specific method?

In my current project, I am utilizing ag-grid to create a dynamic web-application that combines tools from various Excel files into one cohesive platform. One of the Excel features I am currently working on involves displaying a description when hovering ...

Troubleshooting a perplexing problem with an unresponsive AngularJS directive

Here is the code from my app.js file (main JavaScript file) var currentUserId; window.myApp = angular.module('myApp', ['ajoslin.mobile-navigate', 'ngMobile', 'myApp.Registermdl', 'ngProgress', &apo ...

Tips for avoiding cropped images on mobile websites:

I recently created a website that looks perfect on desktop but appears cropped on mobile devices. The site in question is doc.awsri.com Here are the images causing the issue: https://i.stack.imgur.com/eRJXU.png The problem arises when viewing it on a ph ...

How come the values in my object remain inaccessible even after assigning values to it with navigator.geolocation.getCurrentPosition() and returning it?

After successfully assigning values to my pos object within the whereAmI function using navigator.geolocation.getCurrentPosition(), I can confirm that lat and lng are present inside the object. However, attempting to access these properties later on resu ...

ReferenceError: source is not defined in Gulp with Browserify

I encountered a strange error while working on my project. The error message I received is as follows: $ gulp browserify [01:21:03] Using gulpfile F:\CSC Assignments\FinalProject\HotelProject\gulpfile.js [01:21:03] Starting 'bro ...

What is the most effective way to utilize zoom with an Orthographic projection?

I'm attempting to utilize THREE.OrbitControls for zooming in an orthographic projection, but I'm not achieving the desired outcome. I believe it may be possible to adjust the viewSize that is multiplied by left, right, top, and bottom to achieve ...

Using a JQuery for loop to update the value of an input field based on the selected option's attribute, with only the last value

I need to simplify this lengthy code snippet, which is currently functioning well: $(document).ready(function() { $("#PayRate1").change(function() { $('#HourlyRate1').val($('option:selected', this).data('rate')); ...

Integrating various object properties in Angular's select ng-options: A comprehensive guide

I need to merge text and number properties from JSON to display as select options values by default. The expected output should be: 000.000.0001 - Chicago HTML: <!doctype html> <html ng-app="plunker" > <head> <meta charset="utf-8"& ...

Ways to modify the color of mat-icon within an input field using Angular 6

Here is the code from my HTML file: <div class="input-field"> <div> <input type="text" id="name" required email/> <label for="name">Email: <mat-icon svgIcon="mail" class="change-color"></mat-icon> &l ...