Utilizing JavaScript for validation on an ASPX page within Visual Studio

After entering an email ID in a textbox, the email validation process is initiated. However, it seems that there is an issue where the entire function may not be executed properly.

  <head runat="server">
        <title></title>
         <script type="text/javascript">
             function CheckEmailValidity()
             {
                 var emailInput = document.getElementById('<%=TextBox4.Text %>');<!--TextBox4 captures user input-->
                 var emailPattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
                 if (emailInput.value.length > 0)<!--ensure email field is not empty-->
                 {
                     if (emailPattern.test(emailInput.value))
                     {
                         return true;
                     }
                     else
                     {

                         alert("Please enter a valid email address");<!--alert for invalid email input-->
                         return false;
                     }

                 }
                 else
                 {
                     alert("Please enter some text");
                     return false;
                 }


             }
            </script>
    </head>
    <body>
        <form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" style="margin-left: 340px" Text="Submit" Width="96px" OnClick="Button1_Click1" OnClientClick="javascript:CheckEmailValidity();"/>
      </form>
    </body>``

Answer №1

It appears that there are a couple of issues with the IsValidURL function in the JavaScript code. To fix this, please use the code snippet provided below.

function IsValidUrl()
         {
             var emailbox = document.getElementById('<%=TextBox4.ID %>');
             var email = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
             if (emailbox.value.length > 0)
             {
                 if (email.test(emailbox.value))
                 {
                     return true;
                 }
                 else
                 {

                     alert("Please enter a valid email address");
                     return false;
                 }

             }
             else
             {
                 alert("Please enter text");
                 return false;
             }
         }

There are primarily two issues to address:

  1. The line <%=TextBox4.Text %> is attempting to retrieve the value of a textBox, but it should be targeting the ID of the textBox.
  2. When checking the length of the textbox value, make sure to use the correct variable name 'emailbox' instead of 'textbox' for TextBox4.

I hope these corrections solve the problems you were facing.

Answer №2

Perhaps the function you are using is functioning correctly, but the page is still being submitted after validation. To rectify this, replace the following:

OnClientClick="javascript:IsValidUrl();"

with

OnClientClick="return javascript:IsValidUrl();"

Update

I have noticed an error in your JavaScript code. Instead of if (textbox.value.length > 0), it should be

if (emailbox.value.length > 0)
. Please make this change.

Furthermore, there is an issue with

document.getElementById('<%=TextBox4.Text %>')
, which should be
document.getElementById('<%=TextBox4.ID %>')
. In the case of using master pages, it should be
document.getElementById('<%=TextBox4.ClientID %>')
. Please consider making this adjustment as well.

I hope this information proves helpful!

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

Tips for integrating jwt token into axios request

I am facing an issue with my backend endpoint. I can successfully retrieve a list of customers using jwt token on Postman, but when I try to fetch the list from a React app using axios get request, it fails. After reading through this question, I implemen ...

Tips for efficiently delivering the create-react-app index file from your server

I have encountered a challenge in my development work with create-react-app. I am looking to serve the index.html file from the backend initially, but I am facing difficulties in achieving this goal. The main reason behind this desire is to customize the ...

Capture each touchdown and convert it to currency format

As a novice in the field of JS, I have put in a lot of effort into learning from various sources such as websites, documentation, friends, and other questions on Stack Overflow. However, despite all my efforts, I seem to be stuck at this point. $(docume ...

Open up the XML file stored on the local directory

Currently, I am facing an issue while trying to load and explore a local XML file on one of my webpages. The code snippet that I am using is as follows: XmlDocument xmlDoc = new XmlDocument(); string xmlpath = "http://www.xxxx.co.uk/files/myxml.xml&qu ...

Iterating through an array and setting variables according to asynchronous code

I have created a function to loop through an array, call a promise, and update a variable based on the result. The code seems to be functioning correctly, but I am wondering if there is a more optimal way to write it. Any suggestions are appreciated. Tha ...

The package 'models' imported from is not found [ERR_MODULE_NOT_FOUND] error

I'm currently in the process of setting up my project to utilize absolute imports. To accomplish this, I've made adjustments to my jsconfig.json file as shown below: { "compilerOptions": { "baseUrl": "./src&quo ...

Enhance the speed of AJAX search within a UL LI list containing over 5000 objects

Dear Stack community, I've been working on a simple Ajax js search using .addClass and .removeClass as I discovered it's faster than using .show() and .hide(). However, the speed is still not up to par and I'm feeling quite lost. You can ...

An unusual 'GET' request has been made to the '/json/version' endpoint in Express.js

Hey there, I'm facing a challenge with my Express project. For some reason, I keep receiving a 404 error due to a mysterious GET request to '/json/version'. The request seems to bypass the defined routers after adding session data and eventu ...

Retrieving PHP data with jQuery

Isn't it interesting that I couldn't find anything on Google, but I believe you can assist me. I have a Table containing different accounts. Upon clicking on a specific row, I want another table related to that account to slide in. This secondary ...

Executing an SQL delete query with a button click using a JavaScript function in PHP

I have created a setup with three essential files - index.html, database.php, and function.js. In database.php, there is a form generated containing a delete button that triggers the deletion SQL query when clicked. The primary objective is to present a ta ...

Exploring the Open method in AJAX and its impact on synchronicity

I am in the process of creating a webpage that utilizes the openweathermap.org API. However, I am encountering an issue when making an AJAX call and trying to access the API using weather.open(blah, blah, true). function executeWeatherCity(cityName){ ...

What is the process of retrieving data from a Nextjs API route during the build and deployment stages?

I'm currently facing an issue while trying to deploy my nextjs web app on vercel. Upon deployment, I encounter the following error: > Build error occurred FetchError: request to http://localhost:3000/api/products failed, reason: connect ECONNREFUS ...

Currently, I am expanding my knowledge of PHP and MySQL by working on a dynamic form that utilizes arrays. As I progress through the project,

One of my recent projects involved creating dynamic rows in a form using code. I managed to save the data in an array and display it using a foreach loop, but I'm facing challenges when trying to insert this data into a database. Here's a glimps ...

How to dynamically insert a key into an array by locating a specific value in AngularJS

I need help adding a new key to a JSON array by searching for a specific key value. For example JSON:- [ { "$id": "2025", "ID": 41, "Name": "APPLE" }, { "$id": "2026", "ID": 45, "Name": "MANGO" }, { "$id": "2027", ...

Is it possible to retrieve the index of a particular element within an array during an update operation in MongoDB?

After executing the following update statement const result = await Post.updateOne({_id: postId},{ $pull: {reacts: {publisher: req.query.publisher}}, $inc: {postPoints: - reactsEnum[ReactType]} }); I am interested in obtaining the ...

Distinguishing between a regular JavaScript variable and one annotated with a dollar sign

Many responses have addressed the question of using a dollar sign in JavaScript variables. In essence, the dollar sign functions as an identifier in JavaScript variables. However, I am curious if there are other distinctions between regular variables and ...

Inadvertent scroll actions causing unexpected value changes in Material UI sliders

I am currently working on a React application that utilizes Material UI, with slider components integrated throughout the interface. However, I have encountered an issue when using a touch screen device - unintentional changes to the slider values occur wh ...

Ways to verify if both the select and input fields are selected and populated with jQuery

In my html form, I have a select field and an input box with two classes being used: work_phone_class and work_phone_class_input. I am triggering ajax by clicking a save button with a specific class whenever the value in the select field is changed or any ...

Utilizing jQuery to automatically populate fields in an Android WebView when loading a URL

I have been able to achieve the desired output by using the following code in JS: mWebView.loadUrl("javascript:{document.getElementsByName('emailaddress')[0].value = '"+username+"'; document.getElementsByName('password')[0].v ...

Cross-domain scripting with JavaScript

I currently manage 2 subdomains securityservices.example.com workstations.example.com All workstations are associated with the workstations.example.com One of the workstations, known as WS789012 on the domain, is fully qualified as: WS789012.workst ...