Troubleshooting regex validation issues in a JSFiddle form

Link to JSFiddle

I encountered an issue with JSFiddle and I am having trouble figuring out the root cause. My aim is to validate an input using a regex pattern for a person's name.

$("document").ready(function() {
  function validateForm() {
    var userName = $("input[name=userName]").val();
    var subject = $("input[name=subject]").val();
    var message = $("input[name=message]").val();

    if (/^[a-zA-Z ]{2,30}$/.test(userName)) {
      alert("Your name is in the correct format");
    } else {
      alert("Your name can't contain numbers or special characters.");
    }
  }
})

Answer №1

Everything looks good from my perspective, but I suggest incorporating return false to stop the form from submitting the formData.

Furthermore, it is advisable to separate the JavaScript logic from the HTML structure.

$("document").ready(function(){
    $('form').on('submit', function() {
        var userName = $("input[name=userName]").val();
        var subject = $("input[name=subject]").val();
        var message = $("input[name=message]").val();
        if (/^[a-zA-Z ]{2,30}$/.test(userName)) {
             alert("Your name is correctly formatted");
        }
        else{
            alert("Your name cannot contain numbers or special characters.");
            return false;
        }
    });
});

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

Creating a type definition for the createSelector function based on the useQuery result

Struggling to find the correct typings for the createSelector res parameter from redux-js, especially in TypeScript where there are no examples or explanations available. The only guidance is provided in JS. const selectFacts = React.useMemo(() => { ...

Generating table rows using JSON data retrieved from an Ajax response failed due to an 'Invalid Character' error

I have managed to successfully retrieve the response as a JSON from my C# code behind. However, when trying to convert the JSON into a table using jQuery, it is throwing an error ('Invalid Character'). Here is the code snippet: $('#reports& ...

Issue with launching Android application from website

I am looking to add a feature to my Android app that will open the app when a specific link (for example, www.example.org) is visited in the web browser. I have been experimenting with intent filters, but haven't had much success so far. Although I h ...

Loading Ajax content into div (Wordpress) without pre-loading the font can cause display issues

Currently, I'm implementing a JavaScript function within Wordpress using Ajax to load the content of a post into a modal div when specific elements are clicked. Here is an example of how the JS function appears: function openProjectModal($that) { ...

Inconsistency with Mobile Viewport Problem

Apologies for the chaos below, but I've spent quite some time attempting to fix this on my own. It's time to surrender and seek assistance! Here are some screenshots to illustrate the issue: The problem is that sometimes the webpage functions c ...

Interacting between Angular controllers and services to efficiently showcase JSON information

Recently, I started working with Angular 1.5+ and I'm facing some challenges with the basics, particularly when it comes to displaying data from a JSON file on the DOM. Although I can fetch the data successfully (at least I think so, as it console lo ...

Data is persisted in the database even when an error occurs

When a user submits their Permanent Account Number (PAN), I check if it already exists in the database. If it does, I receive an error message stating that the PAN number is already registered. However, if I ignore the error and proceed without changing th ...

Proceed with executing the function only if the current date is before the specified date

I've created a countdown timer that can count both up and down from a given date. However, I want the countdown to only run in reverse and stop once it reaches the current date or any future dates. Currently, the alert message shows when the date is r ...

The BeautifulSoup parsing result differs from the code of the original HTML page

Lately, I've been using BeautifulSoup4 to scrape data from Spotify Charts. It's been working smoothly for a few weeks until today when it suddenly started giving NaN values for all the entries... I suspect that the issue lies in the parsed HTML ...

Updating Arrays in Node.js isn't happening as expected

Hello, I have a function that I am calling from my controller like this: var getLastPoll = await socketModel. getPollOptionsByPollId(data.poll_id); but the controller is returning an empty array as a result. However, when I log the result in my model, ...

Controlling MYSQL data is not possible

When I retrieve data from the database, everything is functioning correctly, but the data flow seems uncontrolled. Here is a snippet of my code... <?php session_start(); include 'conn.php'; include '../includes/layouts/header.php'; ...

Modifying variable assignments in an Angular index.html file according to the environment

Is it possible to dynamically set the config.apiKey value in Angular based on different environments such as Development and Production? In a Production environment, use config.appKey = 'AB-AAB-AAB-MPR'; In a Development environment, use config ...

Unselecting a span in AngularJS: Switching selection to another span

Whenever I click on an item from my list displayed using ngrepeat, it generates another list specific to the selected element. My goal is to change the background color of the clicked element to indicate it has been selected. However, the problem arises wh ...

I am experiencing an issue where the onChange event is not being triggered in my React application

I am currently in the process of creating a random football team picker and handling the database on my own. However, I seem to be encountering issues with the inputs. import React, { use, useRef, useState } from "react"; const fetchAll = async ...

Can someone explain to me how I can customize the background of a bootstrap container?

Currently, I am working on an EJS login project and I have created a style.css file with the following code: [theme="bloodRed"] { background-color: #ff2424; color: #e571e1; accent-color: #00ff00; } In my register.ejs ...

In client.js, learn how to retrieve the value of an input tag (Name) from a login form

Let me explain the situation at hand: I'm currently in the process of developing a chat application using socket.io and NodeJS (Express). Initially, I had a simple prompt that asked for the user's name, easily accessible through const name = pro ...

Using TypeScript with Node.js and Sequelize - the process of converting a value to a number and then back to a string within a map function using the OR

Currently, I am facing a challenge in performing addition on currency prices stored as an array of objects. The issue arises from the fact that the currency type can vary among 3 different types within the array of objects. The main hurdle I encounter is ...

Refreshing material ui select choices based on user input

Just getting started with Reactjs and I need some help. I have a material ui select element that has default values set, and when I click the 'ADD USER' button and submit, I can add new values to the select element. I'm also able to delete o ...

Navigating the same origin policy in Mozilla: A step-by-step guide

I have implemented YUI autocomplete in my project by creating a web service that provides suggestions. Everything works fine when both the application and the web service are deployed on the same machine. However, when I deploy the web service on a differe ...

Analyzing and refreshing the data entries in firebase database

https://i.stack.imgur.com/ZMjck.png I have been attempting to modify my Username password group name. However, the update process is not successful. I am looking for a way to compare data before updating fields, but I am unable to find a suitable method. ...