Validating Email Input Using jQuery

I'm struggling to validate the value of an email input using this code. It's not working as expected and I could really use some assistance, please!

HTML

<input type="text" name="email" class="emailInput" /> 
<button class="validateEmail">VALIDATE</button>

JQUERY

$(document).ready(function(){
    var userEmail = $(".emailInput").val();
    var emailValidation = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; 

    $(".validateEmail").click(function(){
        if (emailValidation.test(userEmail)) {
            alert("Email is valid!");
        } else {
            alert("Invalid email address.");
        }
   });
});

JSFiddle: View Demo

Answer №1

If you're looking for a simple way to implement form validation, consider using the jQuery validation library. It provides easy implementation of various validations, such as checking for required fields and valid email formats.

$( "#myform" ).validate({
  rules: {
    field: {
      required: true,
      email: true
    }
  }
});

For more information, check out the documentation at jQuery Validation

Answer №2

The value of mailVal will not be the same as setMail. To ensure a match, use: mailVal.test($(".mail").val()) instead of using the == comparison.

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

Ways to adjust the CSS height of a fluid body and flexible footer

In a nutshell, I'm dealing with 3 elements: <div> <Header/> </div> <div> <Body/> </div> <div> <Footer/> </div> The header has a fixed height. ...

Is it possible to retrieve the current selector as a string in LESS?

Is there a way to utilize the name of my css classes to specify the URL for an image they depend on? I know that using an ampersand within a selector allows you to add additional states, but can it be accessed as a string? For example: .my-image{ back ...

Comparison between sending JSON data through a form submission versus using jQuery/AJAX

My process involves a basic form that successfully allows me to create a new project using the Asana API <form action="https://app.asana.com/api/1.0/projects" id="newProject" method="post" name="myform"> <input id="name" name="name" type="tex ...

Does the utilization of setTimeout(function, 100) have an impact on performance?

I have implemented a function that continuously checks if the URL contains any of the navigation hrefs every 100ms. If it finds a match, specific elements are assigned the class active. Here's the code snippet: var checkActive = function(){ ...

Ways to decrease the saturation of a background image within a div using CSS

I've come across many plugins that can desaturate an image within the tag. However, I haven't been able to find a solution for desaturating a background image that is used for an element (div). Is there a way to desaturate the background image ...

"Trouble ensues when OrbitControls fail to function properly while loading a

I have a code snippet that displays a 3D file (obj, stl, 3mf) uploaded by the user using three.js OBJLoader, STLLoader, and 3MFLoader. Everything seems to be working fine, but I attempted to integrate OrbitControls so users can zoom in, zoom out, rotate, e ...

Issue with menu height persisting while resizing screen

For my responsive design project, I am implementing a menu that switches to a menu button when the width is less than or equal to 768px. Currently, I am using jQuery to dynamically adjust the height of the menu when the menu button is clicked. The jQuery ...

Customize the behavior of the focus-visible feature on input elements

In my design, I want to remove the outline ring on an input element when it's focused via mouse interaction but still keep it visible when focused using the keyboard. This similar question was raised about a week ago here, unfortunately with no solut ...

What is the method for increasing the left margin of the back button on the default header in React Native?

My attempt to increase the space on the back button from the left side of the header in my React Native code has been unsuccessful. headerStyle: { paddingLeft: 60 } https://i.stack.imgur.com/0RFb0.png I also experimented with adding margin ...

Tips for showing an image in a PHP document

UPDATE: Successfully resolved the issue by avoiding absolute file paths (../Images\City of Bath College Logo.jpg). 2nd UPDATE: Also implemented the same fix for the CSS file and now it functions "the HTML way". I'm encountering a problem displa ...

Switch button while moving cursor

I'm struggling with getting this 2048x512 image, which has 4 stages of transition, to work properly. https://i.sstatic.net/1PBvX.png While I know how to switch it to the final stage on hover, I can't seem to figure out how to incorporate a trans ...

Deciphering JavaScript's Minus Equals Operator: What's the Significance?

Can you explain the significance of the minus equals symbol -= in the following code snippet? $('#wrapper').animate({ backgroundPosition: '-=2px' })(); Appreciate your help! ...

Executing a function on a dynamically generated JavaScript button

Is there a way to create a button that triggers an onClick event calling a function with the signature deleteEntry(entry)? I'm encountering an error stating that entry is undefined even though I have used it in the same function. Adding escape charact ...

Creating a single-level menu with Bootstrap using nested angular ng-repeat

I am currently working on developing a single level menu using bootstrap and angularJS. The menu is successfully functioning with JavaScript and HTML when the <li> element is dynamically created. Now, I am attempting to integrate AngularJS into the ...

Issue: Bootstrap collapsed section remains open when clicking a new link to toggle another section

I am in the midst of creating a one-page layout, featuring collapsible content in the menu. Rather than utilizing a Bootstrap menu for this collapsed content, I have opted to use the ahref elements to display the content of each respective link. One issue ...

Is it feasible to style individual letters in a word within an input field?

Is it possible to change the styling of individual letters in an input containing text? For example, if the word 'Test' is in the input, can I make the 'Te' bold while leaving the 'st' regular? Alternatively, perhaps I'd ...

Attempting to insert a line break tag within the text using React

Having trouble inserting line breaks in text using React. Can anyone guide me on how to achieve this? I've attempted adding the br tag, but it is displaying as in the browser. Here's a snippet of my code. Appreciate any help or advice. let sp ...

To retrieve data from an AJAX response, you will receive an array in the form of a string

After requesting a list of posts submitted by users from my server, the response I received was a string containing an array of stdClass objects. If it had been an actual array, that would not have been an issue. However, it arrives as a string in the foll ...

Halt the refresh event if the input field is in focus

Is it possible to create a script that checks for page refresh every 10 seconds (if ajax response is 1), while also having a chat box on the page? If the user is focused on and writing in the chatbox, the auto-refresh check should stop. Can this be achiev ...

Passing two variables through a Javascript URL to dynamically update a dropdown menu based on the specified values

What is the best way to send two variables to a JavaScript function in order to modify the dropdown list according to those values? $(document).ready(function() { $("#date").change(function() { $(this).after('<div id="loader">& ...