Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria:

  1. Only accept alphanumeric characters

  2. Allow either "_" or "." (but not both)

This is the code snippet I am currently using:

<input type="text" class="form-control" [maxlength]="50" name="userName" placeholder="User Name"
#userName="ngModel" ngModel [(ngModel)]="UserName" (keypress)="userNameValidation($event)">



userNameValidation(event: any) {
  const pattern = /^[a-zA-Z0-9\_\.]+$/
  const inputChar = String.fromCharCode(!event.charCode ? event.which : event.charCode);
  if (!pattern.test(inputChar)) {
    event.preventDefault();
  }
}

Could someone assist me in implementing the "either/or" condition?

Answer №1

Have you considered utilizing the JS string method string.includes? Refer to the documentation here

nameValidation(event: any) {
  const pattern = /^[a-zA-Z0-9\_\.]+$/
  const char = String.fromCharCode(!event.charCode ? event.which : event.charCode);
  
  let includesDotAndUnderscore = char.includes("_") && char.includes(".");

  if (!pattern.test(char) || includesDotAndUnderscore) {
    event.preventDefault();
  }
}

You could also try replacing inputChar with UserName.

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

Adjusting the width of innerHtml within a React router link to match the parent element's width

My current challenge involves a table where a cell is represented as a link. Within this setup, I am incorporating html content into the text of the link: <TableCell align="left" classes={{root: classes.cellPadding}}> <Link className={classes.l ...

Getting information from a JSON file with several variables: A guide for using node.js, express, and jQuery

In order to minimize the number of Ajax calls, I am attempting to send three variables in a single Ajax response. However, I am facing difficulties when trying to process the data on the client side. Let me elaborate on my issue and if sending multiple var ...

Dynamically changing images in Angular based on a value

Below is the code snippet I have written: I am currently using only an if-else condition, but I want to implement an if-elseif-if condition based on three values in order to change the image accordingly. <img [src]="status.getRequestStatus() == ' ...

HTTP request returns a status code of 200 without any accompanying response data

Attempting to send an http request upon a page refresh in my Angular frontend to a nodejs backend, expecting to receive a token as a response. However, sometimes the request gets cancelled and even when it is successful (status code 200), the token is not ...

What is the best way to extract individual words from a string based on a specified list of tokens?

I am currently working with a list of tokens used to create artificial Japanese words, which is represented by the following array: var syllables = ["chi","tsu","shi","ka","ki","ku","ke","ko","ta","te","to","sa","su","se","so","na","ni","nu","ne","no","ha ...

The tilesloaded event in google.maps.event.addListener is unexpectedly failing to trigger

Today, while testing popover messages on my cordova/ionic app, I compiled the app and noticed that the maps weren't loading. Instead, only my custom "Loading map..." spinning icon kept showing. Upon investigating further, I found that var setMap = n ...

Display picture on webpage in 10 seconds

Hi, I'm working on a website project and I've run into an issue where I need to use JavaScript, but I haven't mastered it yet. I have a background image slideshow set up where a new image appears every 6 seconds. My idea is to have the sec ...

Prevent pinch zoom in webkit (or electron)

Is there a way to prevent pinch zoom in an electron app? I've tried different methods, such as using event.preventDefault() on touchmove/mousemove events in JavaScript, adding meta viewport tags in HTML, adjusting -webkit-text-size-adjust in CSS, and ...

Tips for personalizing the ngx-bootstrap datepicker

I am looking to enhance the ngx-bootstrap datepicker popup by adding a link or button within the calendar to select dates with a single click. I have been exploring ways to customize the datepicker without success. Currently, my project is built using Angu ...

If the first dropdown menu has a sub-element, then the user should be able to select the same value in the second dropdown menu using jQuery

To trigger an alert, two HTML select option dropdowns must both have the value DIP EDU. My current code successfully accomplishes this, but there is a scenario where some options in the first dropdown may contain sub-elements. For example, selecting MBA wi ...

Interacting with Rails controllers through AJAX to trigger a JavaScript function

After exploring numerous stack overflow posts without finding a working solution, I decided to seek help for a well-documented use case. I have a button that should perform the following tasks: When clicked, call a custom controller method to update th ...

Using Jquery for Animation: Tips on Revealing Text After Changing Element Color or Styles

Hey everyone, I ran into a bit of trouble while working with jQuery and trying out some animations. My goal was to make a textbox appear and display text when a button is highlighted, similar to a gallery setup. However, I managed to get halfway through th ...

execute a retrieval query on an html pop-up

I have recently created an HTML web resource that I am displaying when a ribbon button is clicked. Within this popup, there is a dropdown list that I intend to fill with records obtained through a fetchXml query. The issue I'm encountering is that de ...

Ways to access the current element in the Evernote editor that corresponds to the cursor's position?

It seems that Evernote editor uses a Rich Text Editor which differs from the input or textarea tag. Therefore, I am unable to use the provided code to determine its type. Is there a way to retrieve the current element of the Evernote editor where the curso ...

Setting up a Typescript project with a shared package configuration

Before I begin, there are a few premises to consider: I require a shared package that will be included in three other packages, TypeScript, Only one node modules, Ability for multiplatform usage (Windows / Linux), To utilize dependencies from the shared ...

The JQuery function .html() fails to include all the HTML content retrieved from a JSON response

I've created some HTML using PHP's json_encode(), and it looks like this: ob_start(); if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post(); get_template_part( 'template-par ...

Navigating with UI-Router within a single view for both viewing and editing purposes

I have been encountering an issue with changing states between the view page and edit page using UI-Router. Here are some of the things I have attempted: Controller: $stateProvider .state('showViewA', { views: { ...

Problems with the navigation bar scrolling in Bootstrap

The project I'm currently working on is located at zarwanhashem.com If you'd like to see my previous question along with the code, you can check it out here: Bootstrap one page website theme formatting problems Although the selected answer help ...

It can be challenging to manage numerous if-else conditions in JQuery

I am having trouble with my JQuery code that checks multiple conditions. No matter what I enter, it always goes to the else condition. $(function() { $('#installment').on("keydown keyup", check); function check() { var inst = Number($( ...

JavaScript redirecting without refreshing the page

Currently, I am faced with a dilemma involving an Ajax function that calls a remote site, saves data to a database, and then needs to refresh the current page to display the new information. The complication arises from the fact that tabs are being utilize ...