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

Encountering Issues with Formatting InnerHtml Text using RegEx

Technology: React.js I have been working on a custom function in JavaScript to highlight specific words within a code block. The function seems to be functioning correctly, but the highlighting isn't staying after the function is completed. Any ideas ...

Align a button to the left or right based on its position within the layout

On the left side, there is dynamic text and on the right side, a button is displayed as shown below: <div class="dynamic-text"> {{ dynamicText }} </div> <div class="some-button"> < ...

Tips for including parameters in an array of values when using getStaticPaths

I'm trying to retrieve the slug value that corresponds with each number in the getStaticPaths for my page structure: /read/[slug]/[number]. The code I have is as follows: export async function getStaticPaths() { const slugs = await client.fetch( ...

Activate Keyboard and Background in the Bootstrap Modal

I have set up my modal to disable the escape key and backdrop by default. $(modal).modal({ backdrop: "static", keyboard: false }); However, at a later time, I want to enable them again. $(modal).modal({ backdrop: true, keyboard: true }); The is ...

VueJS - Iterating over a list within a vue component causes the list to be empty

Having encountered an issue with the answers provided to my question from yesterday, I have decided to create a new query with additional details. To review the original question, please visit: VueJS - using mustache template strings inside href attribute ...

What do I need to add in order to connect a controller to a form submission?

Let's set the scene: There are multiple newsletter forms scattered across a webpage, all needing to perform the same action. This action involves making an AJAX request with certain data and displaying a message using an alert once the request is comp ...

Generating variables dynamically within a React Native component

In my React Native component, I need to create a variable that will be used multiple times. Each instance of this component should have a different variable name for reference. <View ref={view => { shapeView = view; }} onLayout={({ nativeE ...

Why is the promise not returning an integer value, but instead returning undefined?

My validation process includes checking the integrity of the down streaming data to the server and verifying its existence in the database. The code snippet from model.js: const mongoose = require('mongoose'); const User = new mongoose.Schema({ ...

Trigger an event in Vue with specified parameters

I am attempting to emit a function with parameters in the following way. template: ` <div class="searchDropDown"> <div class="dropdown is-active"> <div class="dropdown-trigger"> <button class="button" aria-haspopup=" ...

Incorporating DefinitelyTyped files into an Angular 2 project: A step-by-step guide

I am currently developing an application using angular 2 and node.js. My current task involves installing typings for the project. In the past, when starting the server and activating the TypeScript compiler, I would encounter a log with various errors rel ...

What is the most effective way to incorporate an Ajax partial page refresh in this specific code snippet?

I'm in the process of updating a specific section on my page. This particular section is enclosed in a division tag with a designated "class name". In order to keep things straightforward and avoid any confusion, I am seeking guidance on how to implem ...

How can I use map functions to change the border color of specific items when clicked?

I have an array filled with various data. Here is how my Array looks like, const faqData = [ { q: "How Can We Help You?", a: "Find answers to our most frequently asked questions below. If you can't find what you need, pl ...

Arranging individual spans within a div using CSS for perfect alignment

My current code looks like this: <div id='div_selectores' class='row_titulo '> <span class="label_selector" id="lbl_show"></span><span id="div_selector_show"></span> <br /> <span class ...

Getting the Correct Nested Type in TypeScript Conditional Types for Iterables

In my quest to create a type called GoodNestedIterableType, I aim to transform something from Iterable<Iterable<A>> to just A. To illustrate, let's consider the following code snippet: const arr = [ [1, 2, 3], [4, 5, 6], ] type GoodN ...

Retrieve a collection of CSS classes from a StyleSheet by utilizing javascript/jQuery

Similar Question: Is there a way to determine if a CSS class exists using Javascript? I'm wondering if it's possible to check for the presence of a class called 'some-class-name' in CSS. For instance, consider this CSS snippet: & ...

stacking order of floated and positioned elements

After researching on MDN and reading through this insightful blog post, it is suggested that in the absence of a z-index, positioned elements are supposed to stack above float elements when they overlap. However, upon closer examination, the example prov ...

Unable to alter the dimensions of the `symbol` element from an external SVG using CSS, although the other `symbol` within the same document is responsive to styling changes

Could someone help me find the bug in my code related to resizing SVG symbols with CSS? I am able to resize one <symbol> from an external SVG file, but not another <symbol> from the same file. In my CSS, I am trying to change the width and hei ...

Modifying the Inactive Tab Color in Material UI

For my application, I have a specific requirement where the active tab needs to be styled in red and the inactive tab in blue. Here is how the styling is set up: newStyle: { backgroundColor: 'red', '&$selected': { b ...

Try utilizing multiple URLs to trigger separate AJAX requests with a single click

I am looking to utilize multiple JSON files from different URL APIs simultaneously. Each URL will serve a different purpose - populating table headers with one URL, and table information with two or three URLs. Currently, my code looks like this: $(docum ...

Having difficulty with printing a particular div

I need help with printing a specific div containing checkboxes using jQuery. The checkboxes are initially checked based on data from a database, but when I try to print the div, the checkboxes remain unchecked in the print view. Below is the code snippet ...