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

Is there a method to incorporate a scroll event into the ng-multi-selectdropdown, a npm package?

Query: I need to incorporate a scroll event in the given html code that triggers when the div is scrolled. However, I am facing issues with implementing a scroll event that works when the elements are being scrolled. <ng-mult ...

Display a sneak peek on a separate tab

I have an editor on my website where users can input and edit their own HTML code. Instead of saving this to a database, I want to display the current user's HTML code in a new window using JavaScript. How can I achieve this without storing the code p ...

Running JavaScript code within views

While dealing with AngularJS, I have an index page that includes a <div ui-view></div>. When a specific URL like #/offers/new is entered, it loads a page such as new-offer.html into the ui-view. In my javascript code block within the index.htm ...

Is it possible to install a Chrome extension specifically for YouTube on Google Chrome?

Hey, I'm trying to eliminate thumbnail images from YouTube. The code I am currently using is: while (true) { $("ytd-thumbnail").remove() } As of now, when I input this code in the console, it successfully removes all thumbnail images. However, I ...

The error message "TypeError: Trying to access properties of an undefined object (reading '800')" is being displayed

Every time I launch my application, I encounter the error message: "TypeError: Cannot read properties of undefined (reading '800')". import React, { useState } from 'react'; import { Menu, MenuItem, Avatar, Box, ThemeProvider} ...

Incorporate axios within getStaticProps while utilizing Next.js

I am working on a new project where I am utilizing axios to handle request data. However, I am facing an issue when using axios in the getStaticProps function which results in an error on my index.js page. Here is a snippet of my index.js code: import ...

Experiencing difficulties with executing numerous NodeJs queries

Could someone assist with rendering multiple queries in a Nodejs view? The console shows Promise {pending} and I can't figure out what's causing the issue. I'd appreciate any help or guidance on how to fix this problem. router.get('/ ...

Tips for making a website display in landscape mode rather than portrait orientation

As a newcomer to web design, I am curious if it is feasible to create a website that automatically rotates to landscape view when accessed on a mobile device. The current project I am working on is fluid in design, so this feature would greatly enhance t ...

Is it advisable to hold off until the document.onload event occurs?

I'm working with a basic HTML file where I need to generate SVGs based on data retrieved through an AJAX call. Do I need to ensure the document is fully loaded by enclosing my code within a document.onload = function() { ... } block, or can I assume ...

Stop fullscreen mode in Angular after initiating in fullscreen mode

Issue with exiting full screen on Angular when starting Chrome in full-screen mode. HTML: <hello name="{{ name }}"></hello> <a href="https://angular-go-full-screen-f11-key.stackblitz.io" target="_blank" style=& ...

jQuery load() function triggers unexpected error in jQuery plugin

Here is the current structure of my page: <body> <div id="menuBar"> </div> <canvas id="myCanvas" width="700" height="700" style="border:1px solid #000000;"></canvas> </body> <script src="../Scripts/jQuery.mazeBo ...

The server is constantly sending data through Server Sent Events

I am currently a student working on a project involving a social trading platform. I am looking to incorporate a notification system and believe that SSE would be a great fit for this purpose. However, I am facing an issue where my SSE code is sending data ...

Organizing a set of div elements based on their ID attributes

I am faced with the challenge of sorting a list of divs based on their ID values, which are in the format "indexNumber123". Instead of arranging them alphabetically, I want to sort them numerically as "indexNumber1", "indexNumber2", "indexNumber3" before d ...

Vue.JS - Dynamically Displaying Property Values Based on Other Property and Concatenating with

I have a reusable component in Vue.js called DonutChart. <donut-chart :chartName="graphPrefix + 'PerformanceDay'" /> The value of the property graphPrefix is currently set to site1. It is used as part of the identifier for the div id ...

Dynamic resizing in NextJs does not trigger a re-render

My goal is to dynamically pass the width value to a component's styles. Everything works fine on initial load, but when I resize the window, the component fails to re-render even though the hook is functioning as intended. I came across some informat ...

Add a variable from a callback function in AJAX's success response

Is there a way to effectively utilize the variable in the appended message of the AJAX success call? http://codepen.io/anon/pen/fdBvn data['name'] = $('#goofy').val(); $.ajax({ url: '/api/1/email/test/', data: data, type ...

Issue encountered in Babel version 6 with the transform-es2015-classes plugin in loose mode, causing a SyntaxError when using async/await

After updating to the latest version of Babel v6, I encountered an issue with the transform-es2015-classes plugin in loose mode (https://github.com/bkonkle/babel-preset-es2015-loose/blob/master/index.js#L8) causing problems with async/await functions. Here ...

Step-by-step guide on sorting WordPress posts by a custom field date

I've created an event sidebar section that will only show the next 3 upcoming events. I have successfully set up the custom post type and custom fields, but I am struggling to figure out how to order the posts based on the start date of the events, wh ...

Getting PHP Post data into a jQuery ajax request can be achieved by using the `$_POST

I'm struggling to figure out how to pass the blog title into the data field of my ajax call. I've been searching for beginner tutorials on SQL, PHP, and AJAX, but haven't found anything that clarifies this issue. If anyone knows of any usefu ...

Tips for implementing PHP Instagram Signature using AJAX

I'm facing a challenge with the latest Instagram API, which now requires an Enforced Signed request that includes both an Access Token and Client Secret to generate a Signature. If anyone could spare some time to help me out, I would greatly apprecia ...