String validation using regular expressions

Below is the code I am using to validate a string using regular expressions (RegEx):

if(!this.validate(this.form.get('Id').value)) {
  this.showErrorStatus('Enter valid ID');
  return;
}

validate(id) {
  var patt = new RegExp("^[a-zA-Z0-9.]{1,}$");
  return patt.test(id);
}

The following strings should be accepted:

santosh.jadi
santosh.jadi.others

The following strings should not be accepted:

.santosh.jadi
santosh.jadi.
santosh..jadi

Can someone please explain to me what I might be missing?

Answer №1

Regular expressions used: /^[a-z]+([.-]?[a-z]+)?$/

Sample script:

let inputText = 'abc.def';
let regexPattern = /^[a-z]+([\.\-]?[a-z]+)?$/;
if (inputText.match(regexPattern)) {
  console.log("Match found!");
} else {
  console.log("No match found.");
}

We hope this example code is helpful for your understanding.

Answer №2

Here is a regular expression that matches patterns like /^[a-zA-Z]+[.][a-zA-Z]+$/gm:

^                           // starting position
  [a-zA-Z]                  // matching letters
  +                         // matching 1 or more times
  [.]                       // matching a period
  [a-zA-Z]                  // matching letters
  +                         // matching 1 or more times
$                           // ending position

var rgx = /^[a-zA-Z]+[.][a-zA-Z]+$/gm

console.log(rgx.test('chris.zimmerman'))
console.log(rgx.test('.chris.zimmerman.'))
console.log(rgx.test('chris..zimmerman'))
console.log(rgx.test('ch3ris.zimmerman'))

If you need to allow multiple dots, such as in the pattern chris.w.zimmerman, you can use this regular expression: ^[a-zA-Z]+([.][a-zA-Z]+)+$

var rgx = /^[a-zA-Z]+([.][a-zA-Z]+)+$/gm

console.log(rgx.test('chris.zimmerman'))
console.log(rgx.test('chris..zimmerman.'))
console.log(rgx.test('chris.zimmerman.'))
console.log(rgx.test('chris.w.zimmerman'))

Answer №3

Success! Check out the regex pattern ^[a-zA-Z]+([\.\-]?[a-zA-Z]+)+$

if(!this.validate(this.form.get('Id').value)) {
  this.showErrorStatus('Enter valid ID');
  return;
}

validate(id) {
  var guard = new RegExp("^[a-zA-Z]+([\.\-]?[a-zA-Z]+)+$");
  return guard.test(id);
}

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

Tips for stopping automatic scrolling (universal solution)

Issue or Inquiry I am seeking a way to disable actual scrolling on an element while still utilizing a scrollbar for convenience (avoiding the need for manual JavaScript implementations instead of relying on browser functions). If anyone has an improved s ...

automatically loading data using jquery

I am currently utilizing a windows service along with an html+j query page to interact with a web service. Whenever a Document is scanned on our device, I aim to display: name, country, and Passport number on our webpage. Although I have successfully a ...

Issue: Unauthorized access: nodeMailer despite correct configuration

Having trouble with an error when using the less app option on Gmail. I don't have 2-factor authentication enabled, and my credentials are correct. I can log in to my file to verify this, but the error still persists. const nodemailer = require(" ...

What is the relationship between html, body, and window when scrolling through code?

I've been working on adding a scroll-to-top button to my website. After doing some research online, I came across this code snippet: $('html, body').animate({scrollTop:0}, 'slow'); It's interesting that they are trying to scr ...

Ways to extract information from a database using a parameter

I am currently working with angular cli version 8.1.0 and I have a requirement to pass parameters in the URL and retrieve data from a PHP MySQL database. On the PHP side, everything is functioning correctly and the URL looks like this: http://localhost/rep ...

The value of the progress bar in Bootstrap Vue cannot be retrieved using a function

I have implemented a progress bar using Bootstrap Vue. Here is the HTML code: <b-progress :value="getOverallScore" :max=5 variant="primary" animated></b-progress> The getOverallScore function calculates an average value based on three differe ...

Perform a task upon clicking the JavaScript menu

Implementing dropdown menu items using a text link with JavaScript and CSS. You can view a demo here. I am looking to trigger an action when each menu item is clicked. Currently, they are not behaving as expected. HTML: <span class="inline-dropdown- ...

Disabling the 'fixed navigation bar' feature for mobile devices

Here's a code snippet that I'm working with. It has the ability to make the navigation stick to the top of the page when scrolled to. HTML <script> $(document).ready(function() { var nav = $("#nav"); var position = nav.position(); ...

I'm having trouble getting my nav-tab to function properly in Bootstrap 4 when used with Angular 4. Can

I have been attempting to utilize Bootstrap 4 tabs with Angular 4 with the expectation that it would resemble and function similar to this example enter link description here However, my page is displaying like this. https://i.sstatic.net/dymNH.png Here ...

Typescript Array does not adhere to correct data type

Why does the code below fail to transpile when pushing a new instance of class B into an array that is typed as only accepting instances of class A? class A {}; class B {}; const arr: A[] = []; arr.push(new B()); ...

Is it possible to hide the <dd> elements within a <dl> using knockout's custom data binding upon initialization?

I have implemented a <dl> where the <dd> can be expanded/collapsed by clicking on the corresponding <dt> using knockout's data binding. The inspiration for my solution came from a tutorial on creating custom bindings. Currently, I h ...

Move on to the next iteration in the FOR loop in Node JS

Is there a way to skip item 3 in the loop without breaking it? for (var i = 1; i<= 9; i++) { if (i==3) break; console.log(i); } I had a tough time searching for an answer online because I am unsure of the exact terminology to use. Desired output: ...

Why ngIf in Angular Ionic doesn't correctly compare arrays from parent when using the 'includes' method?

I have implemented a feature where users can select their interests through a dialog. When a user clicks on a chip, the following method is triggered: handleClick(tag){ let found = false; let index = -1; // tslint:disable-next-line:prefer-for-of for (let ...

Using ES6 syntax, ignite the React function

Below is the code snippet provided: class Seismo extends Component { constructor(props) { super(props); this.state = { news: "" } this.updateNews = this.updateNews.bind(this) } updateNews = () => { console.log('te ...

Tips for maintaining server session by tracking user activity on the browser using a simple ajax request to the server without relying on JQuery

In my website, the server session Timeout is set to 30 minutes. <system.web> <sessionState timeout="30" /> </system.web> However, if a user is actively engaging with the site by typing a long comment or selecting chec ...

Using the md-date-picker along with the md-menu component

Whenever I try to click on the md-date-picker inside md-menu, it unexpectedly closes. You can view the issue on this CodePen link. This seems to be a bug related to ng-material as discussed in this GitHub issue. Any suggestions for a workaround? Here is t ...

Angularjs scope's parent id

I'm looking to access or manipulate a scope's grandparent without making things overly complicated. Leveraging the controller as syntax, I can reference the parent controller like so: this.applicationCtrl.something with applicationCtrl > paren ...

Validating Inputs with an Array of Values in my Angular 2 Application

I have been exploring ways to retrieve data from an array of values instead of a single value when using [(ngModel)] binding in my Angular 2 application. The current setup functions perfectly with a single value, as shown below. The data is pulled from the ...

How to extract selected value from a dropdown menu in a React component

Is there a way for me to retrieve the chosen value from the dropdown menu? The select dropdown contains 12 options. My goal is to capture the selected value and then utilize it in handlecolumnchange to manipulate the number of columns added or removed. Des ...

Is Node.js functioning properly, but how can I incorporate it into a web browser?

I have a SQL Server table that I want to display in a web browser using the DataTables jQuery plugin. The code below works well for outputting data in the command line, but I need it to be displayed in the browser, possibly in JSON format. I am utilizing ...