Using Javascript is a great method to efficiently confirm if a given name is made up of specific characters

My current project involves creating a system that requires users to input multiple names of their choosing. To ensure the validity of these names, I am looking to develop a "name verifier" that checks if all characters in the entered string are either letters (both lowercase and uppercase), numbers, or a few select special characters (such as , : . * _ - +).

One approach I considered was to define a large constant array containing all permitted characters and then iterate over the input string using the following method:

for (i = 0; i < name.length; i++){
  if (permitted_chars.indexOf(name[i]) === -1) return false;
}
return true;

However, given the potentially extensive size of both the array of permitted characters and the names themselves (not to mention the effort required to create the array), this approach seems impractical.

Are there any alternative methods that could be more efficient?

Answer №1

One effective method is using a regular expression. If regular expressions are unfamiliar to you, I recommend taking the time to learn more about them. They are incredibly useful for searching and validating strings.

var string = "Abcd_1234";
var regex = new RegExp("^[a-zA-Z0-9_]*$");
regex.test(string) //=> true

I hope this explanation is helpful!

Answer №2

If you need to check for specific characters in a string, you can utilize the power of regular expressions

var disallowedChars = ['@', '$', '#'];
var regex = new RegExp('[\\'+disallowedChars.join('\\')+']');
regex.test("hello") #=> false
regex.test("hello$") #=> true

var input = "input with @ character"
if(regex.test(input))
    alert('Invalid characters found')

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

How to Utilize Custom Component Tag Names in CSS with Vue.js 2?

<template> <header> <hamburger></hamburger> <app-title></app-title> <lives></lives> </header> </template> <script> export default { name: 'Titlebar& ...

The issue of memory leakage in Three.js

I have come across an unusual memory leak in three.js (r73). Here are the steps to reproduce it: 1) Go to the following link using Google Chrome (version 46.0.2490.80 m) 2) Open DevTools -> Profiles -> Take Heap Snapshot. Check out my screenshot be ...

Best Practices for Implementing AJAX Requests in jQuery

It's perplexing how similar they seem, making me unsure when to use the $.ajax() method versus the $.get() or $.post() methods in jQuery AJAX. I find myself leaning towards using $.post(), as the complexity of $.ajax() often leaves me baffled. ...

What is the best way to connect two buttons in separate divs?

I'm facing a challenge of adding two buttons side by side when they are located in different div elements. I've tried using the float property in the btn-group, but it interferes with the functionality of the dropdown and affects the animation. H ...

What is the best way to establish a default search query within the vue-multiselect component?

I have incorporated vue-multiselect into my project. You can find more information about it here. This is a snippet of my template structure: <multiselect v-model="value" :options="options" searchable="true"></multiselect> When I open the mu ...

Automatically submitting a form in React.js based on certain conditions being met

Does anyone have experience with React login and register form buttons that trigger Redux actions? I'm facing an issue where both actions are being dispatched at the same time when certain conditions are met. Here is my code snippet: const LoginPage ...

What's the best way to keep track of the number of objects I've created

Using this HTML code, I can create member objects. However, I also need to determine the count of these member objects for certain calculations. Additionally, when a member object is deleted, the count of member objects should be reduced accordingly. The ...

Display list items in HTML based on the length of an array

In my backend, I have a user-defined array of cars. If the user selects 3 cars, the array will contain 3 elements. I would like to display specific details of the cars in HTML elements within a list. The array is based on JavaScript. Here is an example of ...

Obtaining the sub-domain on a Next.js page

Looking at my pages/index.tsx file in Next.js, the code structure is as follows: import { ApolloProvider } from "@apollo/react-hooks" import Client from "../db" import Header from "../components/Header" export default function Index() { return <A ...

What is the best way to deactivate a submit button while an AJAX request is underway, and then reactivate it once a successful AJAX response is

I am working with the following HTML code: <form action="view_rebate_master.php" method="post"> <div class="form-group"> <label for="company_name" class="col-lg-12">Manufacturer</label> <div class="col-lg-12"> ...

Combining multiple Float32Arrays to create a single Float32Array

I need help creating a function that can flatten multiple Float32Arrays into one large Float32Array const first = new Float32Array([1,2]); const second = new Float32Array([3,4,5]); const third = new Float32Array([6,7,8,9]); const chunks = [ ...

Implement Meteor authentication with Google OAuth

I'm attempting to set up a basic login button for my Meteor app using google oauth. I followed these steps: mrt create accounts mrt add accounts-google mrt add accounts-ui I removed the default html/css/js files and instead added: client/index.html ...

Hiding Modal Box Upon User Login: A Step-by-Step Guide

After a user clicks the login button in my navigation, a modal box pops up. However, once the user logs in, the modal box does not disappear. How can I hide or remove the modal box when users click on the login button? This code snippet is from Home.vue: ...

Retrieve the JSON data based on a specific key after a specified period

Hello there, I am encountering an issue with a specific JSON key. Let's say I have an external file containing JSON data structured like this: { "key 1":[ { "linkName":"key name 1.1", "linkUrl":"key URL 1.1" }, ...

Finding your way through Bootstrap Datepicker using the Previous and Next Buttons

Is there a way to implement Previous and Next Button functionality for navigating a Bootstrap Datepicker using jQuery, similar to the illustration below? https://i.sstatic.net/e9I7P.png I attempted the following approach: function PrevNext(isnextbtn) ...

Neither .getJSON() nor .ajax() are functioning for making a REST API call

Could someone please explain how to execute a REST call using jQuery or JavaScript? I attempted to use both .getJSON() and .ajax(), but neither worked for me. Here is the URL for the REST service: Sample Code: $.getJSON('http://ws1.airnowgateway.or ...

What is the best approach to get a successful response from an asynchronous method in Express?

Still grappling with the concept of Node's non-blocking nature. The code below executes as expected, but I'm curious if there's a more efficient way to achieve the same result. The route is taking 3 parameters (zipcode, type, rad) and using ...

Switching buttons with AngularJS

I am currently working on a Github search app using the Github API in Angular. My goal is to make it so that when the user clicks the "Add to Favorite" button, the button disappears and the "Remove Favorite" button is displayed instead. I attempted to achi ...

What is the best method to deactivate zoom in/out buttons using JavaScript?

As a newcomer to Phonegap, I've managed to implement zoom in/out functionality using websettings in the .java file. However, I now face a challenge where I need to disable/enable the zoom in/out buttons and stop scrolling at a specific point. I attemp ...

What is the process of converting Luxon DateTime format into a string or numerical representation?

After setting up a Luxon clock for my project, I am facing an issue while using a component to define the month number of the current date. import { DateTime } from 'luxon'; import React, { useEffect, useState } from 'react'; interface ...