What is the best way to implement a text box that only accepts characters and numbers in Vue.js?

 methods: {      
      isEmail(e) {
       let char = String.fromCharCode(e.keyCode); // Get the character
       if(/^[A-Za-z0-9*,&,@]+$/.test(char)) return true; // Match with regex 
       else e.preventDefault(); // If not match, don't add to input text 
                   },
 <input type="email" v-model.trim="$v.email.$model" :class="{'is-invalid': validationStatus($v.email)}" class="input-section" placeholder="Enter your company email ID" :maxlength="maxemail" v-on:keypress="isEmail($event)"> 

<div v-if="!$v.email.required" class="invalid-feedback">The email field is required. 
</div>
<div v-if="!$v.email.maxLength" class="invalid-feedback">30 characters {{ 
$v.email.$params.maxLength.min }} only</div>

My issue is that at present the textbox above is only accepting alpha characters (A to Z and z to A). However, I need it to accept alphanumeric characters (i.e A to Z, a to z, 0 to 9 and special characters like *,&,@). How can I modify the code above to achieve this?

Answer №1

If you're unfamiliar with it, the pattern /^[A-Za-z]+$/ represents a regular expression that currently only allows values from A to Z and a to z.

To address your question directly, I recommend expanding your existing regex by including the missing characters. For example, you could use /^[A-Za-z0-9*&@]+$/

Remember that there are various online tools available for testing and validating your regular expressions.
You can check out one such tool here: https://regex101.com/r/uE4GfO/2

Currently, the validation process seems to be checking character by character, but it would be more efficient (and likely more accurate) to validate the entire string at once.

Furthermore, if you're working on validating an email address specifically, I suggest utilizing a regular expression as detailed in this discussion: Take a look at How to validate an email address in JavaScript

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

I am experiencing difficulty executing a loop that is reliant on a variable from a function

After spending the past day grappling with this issue, I must confess that as a newcomer to coding, my attempt might be a bit messy. Currently, I am working on a bot that requests a JSON file. Below is the code I have managed to put together so far. cons ...

Converting objects into an array of arrays: A Step-by-Step Guide

My attempts have not yielded the desired outcome Object.keys(data).forEach(function (key) { console.log(data[key]); array = $.map(data[key], function(value, index) { return [value]; }); }); The output I encountered is - 0:{1: 2, 2: ...

"Examining the differences between an array containing objects and an array containing IDs

How can I use jQuery to find objects in the allObjects array that have ids matching values in my custom id array? var arrayOfIds = [1, 4, 5]; var allObjects = [{"Id":"1", "name":"aa"},{"Id":"2", "name":"bb"} ,{"Id":"3", "name":"cc"} ,{"Id":"4", "name":"d ...

extracting multiple cookie values and assigning them to variables in Angular

Here is the code snippet I am working with: var ietms = $cookies.get('items'); Although I can retrieve values, they appear in multiples like: Testvalue1|Testvalue2|testvalue3 I would like to separate these three items into individual variabl ...

Checking for IE-9 compatibility during end-to-end testing with the use of phantomJS

In order to test my application for compatibility with IE-9, I am using a combination of PhantomJS (headless end-to-end testing), Selenium WebDriver, and Grunt (task runner). It is crucial that the application functions flawlessly on IE-9. Headless testi ...

Accessing child mailboxes in node-imap

I am having trouble accessing the sub-mailboxes in my primary mailbox. When I try to open them, I encounter an error message in the debug mode that says: 'A5 NO [NONEXISTENT] Unknown Mailbox: INBOX/[Gmail] (Failure)' However, when I check the ...

Transform PHP array into a properly structured array or object that can be easily used in JavaScript

My PHP code contains an array that looks like this: $variation = [ attribute_label => "Choose your Color", attribute_name => "pa_choose-your-color", variations => [ "819" => "Red", "820" => "Blue", ...

Is there a way to manipulate the DOM without relying on a library like jQuery?

My usual go-to method for manipulating the DOM involves jQuery, like this: var mything = $("#mything"); mything.on("click", function() { mything.addClass("red"); mything.html("I have sinned."); }); Now I am looking to achieve the same result usin ...

Difficulty clearing dictionary in Vue.js causing issues with the DOM not updating

Check out this jsfiddle example I am working with a dictionary in Vue and using a v-for loop to render its items. I want to clear the dictionary, but simply setting it to an empty object or deleting keys doesn't trigger a re-render in the DOM. Any su ...

Vue JS projects do not support Tailwind styles

Just getting started with vue js and wanted to create a cool little demonstration. I decided to incorporate tailwindcss into my new project. Here's how I set up the project: vue create vue-tailwind-template Then, I added tailwind using the following ...

Ways to extract the id after clicking

In my code, I have a query called snapshot.forEach that functions similarly to a for loop in looping through all of my Firebase data and displaying it with a div tag containing a click event. When another user clicks on this div tag, the event will retriev ...

Error encountered when bundling FullCalendar Vue with Webpack, specifically related to the /node_modules/@fullcalendar/common/main.css file

I am running into an issue while trying to incorporate @fullcalendar/vue3 with webpack for bundling a sample calendar. My webpack bundler is throwing an error when it encounters the css file, stating that there is an unexpected token. I believe I need to a ...

Exploring the Vue3 reactivity system within the script setup for language localization

When I add DOM elements in the script setup section, I want the messages to dynamically change based on the selected language. Currently, I am using the vue-i18n plugin for internationalization. While it's simple to achieve this in the template sectio ...

I am currently working on developing an HTML and JavaScript audio player that can play audio at specific scheduled times

Looking to create a custom HTML/JavaScript audio player that adjusts playback based on the time of day. For instance, if it's 1:00 pm, the file will start playing from 0:00 minutes; and if it's 1:01 pm, the file will begin playing from 1:00 minut ...

In JavaScript, can you combine values within an array of objects that share the same key value pair?

Here is the JSON data that needs to be merged based on the toolName: [ { "data": { "toolName": "Login", "data": [ { "scrapValue": " Find The ...

Enhance your application with Express Body Parser and tailored headers

Currently, I am setting up a REST API that can handle requests with a custom Content-Type. However, I'm encountering difficulties parsing the body using the NPM package called body-parser. For testing purposes, I am utilizing Mocha and Chai-HTTP to se ...

Adjust the size of horizontal <li> elements dynamically to keep them in a single row

I've been trying to set up a 'gallery' section on one of my pages, with three elements featured. However, I'm running into an issue where resizing the window or viewing on a smaller screen could cause overlaps or force a second row with ...

Having trouble sorting data-text values that include colspan cells

Latest Update: Encountered an issue with incorrect sorting and frozen sortings when dealing with a cell containing the colspan attribute. Refer to https://jsfiddle.net/2zhjsn31/12/ where the problem arises for the date 2018-06-24 On https://jsfiddle.n ...

Using object functions within middleware functions

Within my middleware, I have the following code snippet: const UserMiddleware = { isNumber(n) { return !Number.isNaN(parseFloat(n)) && !Number.isNaN(n - 0); }, // eslint-disable-next-line consistent-return validateSignUp(req, res, next) { ...

"Encountering a halt in my Node.js Application as it waits endlessly

I'm currently following a tutorial on creating a collaborative canvas drawing application using Node.js and Socket.io. I've included the source file below which is used to create the server. However, when I try to open it in my browser, it gets s ...