Guide to verifying Regular Expressions for text fields in JSP with JavaScript

Need help with validating the firstname using regex. The javascript code provided generates an error if the value length is 0, however, even after entering a correct firstname format based on the regex, it still shows 'First name invalid'. I suspect there might be an issue with my else-if block.

Here is the Java Script code:

function validate(){
            var valid = true;
            var regex="([A-Za-z]{3,30}\s*)";

        if (document.getElementById('fname').value.length == 0) {
        validationMessage = validationMessage + '  - First name is missing\r\n';
        document.getElementById('errorFirstNameMissing').style.visibility='visible';
        valid = false;
        }
        else if(document.getElementById('fname').value!=regex){
            validationMessage = validationMessage + '  - First name is not valid can contain only letters from A-z and a-z\r\n';
            document.getElementById('errorFirstNameInValid').style.visibility='visible';
            valid = false;
            }
        else{
            document.getElementById('errorFirstNameMissing').style.visibility='hidden';
            document.getElementById('errorFirstNameInValid').style.visibility='hidden';
        }

        if (valid == false){
        alert(validationMessage);
        }
        return valid;
        }

Here is the JSP code:

<form name="Register" action="RegisterServlet" method="post" onSubmit="return validate()">
<table>
<tr>
<td>First Name* : </td>
<td><input type="text" name="txtFname" id="fname" maxlength="30"/><br/>
<span id="errorFirstNameMissing" style="visibility:hidden;">*Please provide your first 
name.</span><br/>
<span id="errorFirstNameInValid" style="visibility:hidden;">*Please provide a valid first 
name.</span>
</td>
</tr>

Answer №1

When testing regex, it's important to use the correct syntax. Try this instead:

/^([A-Za-z]{3,30}$)/.test(name)

To learn more about using the regex object, check out the documentation on MDN

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

Using Discord.js to filter messages that start with a specific phrase and finding a solution for handling DiscordAPIError when using bulk

This is the code I am currently using. Shout out to @André Dion for the assistance. if (message.channel.type == 'text') { message.channel.fetchMessages().then(messages => { const botMessages = messages.filter(msg => msg.auth ...

What is the best way to create height segments from a cylinder in three.js?

My current project involves a cylinder that is divided into multiple height segments, with the number of segments depending on the specific data. Each height segment contains a value that I want to use for extruding the entire circle at that particular hei ...

Is it possible to modify the sizes parameter of the GPUComputationRenderer?

Currently, I am utilizing gpuCompute = new GPUComputationRenderer( sizeX, sizeY, renderer ); for texture purposes. I am looking to update the values of sizeX and sizeY within this code snippet. However, after searching through the library, I have not been ...

Attempting to assign a thumbnail image to a file on Google Drive by utilizing JavaScript

I've been working on adding thumbnails to the files that I upload to Google Drive using Javascript. I'm following the instructions outlined at https://developers.google.com/drive/v3/web/file#uploading_thumbnails For my web-safe base64 image, I c ...

How to make a node_module global with the power of Webpack 2

I'm currently utilizing a package in an Angular project that can be found at the following link: https://github.com/pablojim/highcharts-ng One of the requirements for this package is that highcharts needs to be included as a global dependency by add ...

Browsing through a JSON document

Currently, I am attempting to extract schedule information from a JSON file called js/schedule.json. The format of this file is as follows: [ {"date":"12/06/2014","day":"Thursday","kick-off":"21:00","team1":"Brazil","team2":"Croatia","group":"A","stage":" ...

Exploring how to use React with a select component featuring objects

Hello, I am new to working with React and I have a question regarding the select component of Material UI. Here's my situation: I am creating functionality for creating and editing a User object. This User object has a primary key and some data, incl ...

I'm looking to enhance my code by adding a new user login password. How can I achieve this?

Currently, I am in the process of adding another user and have been exploring various code snippets available on different websites. I decided to test the following example, which worked perfectly. However, I am now wondering how I can add an additional u ...

Sharing Global Variables in Node.js: What's the Best Way to Pass Them into Required Files?

Recently, I decided to organize my gulpfile.js by splitting it into multiple files within a /gulp folder. However, I encountered an issue when trying to pass a variable debug (boolean) into these files to control the behavior of the gulp command being incl ...

Issue with Firefox: Click event not fired when resize:vertical is set while focusing

Issue: Firefox is not registering the first click event when a textarea has the following CSS: textarea:focus { resize: vertical; } Check out the demo: http://jsbin.com/wuxomaneba/edit?html,css,output The fix for this problem is straightforward - ju ...

attempting to communicate with Postman but encountering an error in the process

Upon attempting to send a request through Postman, I encountered an error. Nodemon is operational and the server is active in the terminal. index.server.js file //jshint esversion:6 const express = require("express"); const env = require("d ...

I am looking for a way to add some color to the text within a div on my HTML page. Can you help me

Is there a way to apply background color only to the text content within this div, without styling the entire element? ...

Rearrange the li elements within multiple ul lists using JavaScript

Is there a way to reorder multiple ul-lists on my website using JavaScript? An example of the lists may be as follows: $(document).ready(function() { var ul = $('ul.filelist'); for (let u = 0; u < ul.length; u++) { const element = ul[ ...

A guide on incorporating and utilizing third-party Cordova plugins in Ionic 5

Attempting to implement this plugin in my Ionic 5 application: https://www.npmjs.com/package/cordova-plugin-k-nfc-acr122u I have added the plugin using cordova plugin add cordova-plugin-k-nfc-acr122u but I am unsure of how to use it. The plugin declares: ...

Accessing an object from an AngularJS controller in an external function

I previously inquired about this issue and received a suggestion to add a service, but it did not solve the problem. I am trying to access a variable from a controller ($scope) within an external function. Below is a snippet of the example: app.controll ...

Looking for assistance with submitting a form?

Looking for assistance with a JavaScript hack. Since this morning, I've been trying to figure out a simple hack that would enable me to submit a form multiple times. Take a look at this image. It's a basic form. What I want is to be able to su ...

Is the "add" feature malfunctioning?

My code is experiencing an issue where the URL and ID are not being passed correctly from one function to another. When I click on a link that contains the add() function, it fails to capture the URL and ID. <a href="#" style="color:#FFF;" onclick="add ...

Pass data back and forth between app.js (node) and javascript (main.js)

I am facing a challenge in sending and retrieving data (username) between app.js and main.js. In my setup, I have a node app.js that calls index.html which then triggers the main.js function called "clicked". Below is the code snippets for each file: app. ...

Integrate new functionality into the plugin's JavaScript code without directly editing the JS file

I need to incorporate a new function called 'setInputDataId' at the same level as the existing function '_select' in the plugin js file without directly modifying the file itself. I am seeking guidance on how to add this new function. ...

What are some effective strategies for bypassing CORS requirements in Vue client-side and server-side applications?

I found this amazing MEVN stack tutorial that I've been following: MEVN Stack Tutorial The tutorial is about creating a blog post app, where the client side is built using Vue (referred to as app A) and the backend is built on Express.js providing d ...