JavaScript-enhanced HTML form validation

I encountered a small glitch while working on simple form validation with JavaScript. I tried to catch the issue but have been unable to do so. Here is the code snippet, where the problem lies in the fact that the select list does not get validated and I'm unsure why.

<html>
<head>
<title>Mobile Phone Prices In Pakistan </title>
<style>
.error{
color:red;

}
</style>


</head>
<body>


<form id="theform" name"form1">
<p>Name:
<input type="text" name="username" id="username" />
<span id="nameerror"></span>
</p>
 <p>
 Email:
 <input type="text" name="email" id="email" />
 <span id="emailerror"></span>
</p>
<p>
Country:
<select name="country" id="country">
<option value="0">choose your country </option>
<option value="pk">pakistan</option>
<option value="ind">India</option>
<option value="afg">afghanistan</option>
<option value="irn">Iran</option>
</select>
<span id="countryerror"></span>
</p>
<p>
Gender
</p>
<p>Male
<input type="radio" name="gender" id="radio" value="radio">
<span id="gendererror"></span>
Femal
<input type="radio" name="gender" id="radio2" value="radio2">
</p>
<p>
<input type="checkbox" name="rules" id="rules">
Accept our rules and regulation to continue with form process 
</p>
<p>
<input type="submit" name="button" id="submit" value="register" >
</p>
</form>



<script type="text/javascript">

document.getElementById("theform").onsubmit = validate;
document.getElementById("submit").disabled = true;
var rules = document.getElementById("rules");
rules.onclick = function (){
    if(rules.checked){
        document.getElementById("submit").disabled = false;

    }else{

        document.getElementById("submit").disabled = true;
    }

}

function validate(){

var username = document.getElementById("username"); 
var email = document.getElementById("email");
var country = document.getElementById("country");       
var radio1 = document.getElementById("radio");  
var radio2 = document.getElementById("radio2"); 
var atpos = email.value.indexOf("@");
var dotpos = email.value.lastIndexOf(".");




if(username.value == "" && username.value.length == 0){

    document.getElementById("nameerror").innerHTML = "please enter your name";
    username.focus();
    document.getElementById("nameerror").className = "error";
    return false;

}else{
    document.getElementById("nameerror").innerHTML = "";
    document.getElementById("nameerror").className= "";
}
if(atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.vlaue.length){

    document.getElementById("emailerror").innerHTML = "please enter your email";
    email.focus();
    document.getElementById("emailerror").className = "error";
    return false;

}else{
    document.getElementById("emailerror").innerHTML = "";
    document.getElementById("emailerror").className= "";
}
if(country.selectedIndex == 0){
    document.getElementById("countryerror").innerHTML = "please choose country";
    document.getElementById("countryerror").className = "error";
    return false;

}else{
    document.getElementById("countryerror").innerHTML = "";
    document.getElementById("countryerror").className = "";

}

if(radio1.checked == false && radio2.checked == false){

    alert("please choose your gender");
    return false;   
}



}


</script>


</body>
</html>

Answer №1

Spelling errors found

if(atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.**vlaue**.length){

Answer №2

The explanation lies in the fact that there was a misspelling of value in the email section.

Here is a functional JSFiddle link for reference: http://jsfiddle.net/v4qv7n7m/1/

Your original code snippet:

if(atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.vlaue.length){

    document.getElementById("emailerror").innerHTML = "please enter your email";
    email.focus();
    document.getElementById("emailerror").className = "error";
    return false;

}else{

Corrected code snippet:

if(atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.value.length){

    document.getElementById("emailerror").innerHTML = "please enter your email";
    email.focus();
    document.getElementById("emailerror").className = "error";
    return false;

}else{

Answer №3

spelling mistake here email.value.length

if(atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.value.length){
                                                      ^^^^^^

}

http://example.com/jsfiddle-link

Answer №4

If you're trying to determine whether the select element has a value, that's what you need to focus on.

Check out this updated version of your code:

<p>Please make sure to choose a Security Question from the dropdown list.<br />
    <select name = "Security Question" id="securityQuestion">
        <option></option>
        <option value="m">What is your Mother's maiden name?</option>
        <option value="p">What is the name of your pet?</option>
        <option value="c">What is your favorite color?</option>
    </select>
    <input type="button" value="Click to Check" onClick="checkDropdown(1)" />
</p>

<script>
    function checkDropdown () {
    var securityQuestionElement = document.getElementById('securityQuestion');
    if(!securityQuestionElement.value) {  
        window.alert('Please select a Security Question.');  
        securityQuestionElement.value = 'm'
        return false;  
    }
}
</script>

Main Changes Made:

I am specifically checking for the select element's value, not the "checked" status of options.
I am targeting the element by its ID for efficiency reasons.
I am checking for the absence of a value rather than matching it with specific cases, making the code cleaner and easier to understand.

Answer №5

There is a typo in your if statement

if(atpos < 1 || dotpos < atpos+2 || dotpos+2 >= email.vlaue.length){

Update email.vlaue.length to email.value.length

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

Using Node.js, Socket.IO, and Express to deliver static JavaScript files served dynamically

I have been working on a node.js application that utilizes socket.io and express. Initially, all of the javascript was included in the HTML file, but now I am looking to separate it into a .js file. In my primary node application, this is what I currently ...

Establish a default route within a Node Express application to handle multiple generic URLs (url/index, url/index2, url/index3, and

Currently, I am in the process of learning React and Express frameworks through exercises provided by NodeSchool.io. My goal is to consolidate all exercise files into a single application with multiple pages named as: index index2 index3 index4 .. ...

Empty results received from MongoDB queries executed within an asynchronous loop

I'm encountering an issue where I have a list of IDs that I need to query Mongo with in a for loop, but it always returns an empty []. Initially, the queries were returning promises, so I switched from using forEach to a standard for loop as shown her ...

In Selenium IDE, the command to locate elements by ID works smoothly, but when using Java, the same

I encountered a challenge while trying to locate a dropdown box. Despite being able to make it work using an absolute path, I struggled with identifying the element by its xpath or id. It's quite frustrating and I'm struggling to find a solution. ...

A guide on merging existing data with fresh data in React and showcasing it simultaneously

As a newcomer to Reactjs, I am facing the following issue: I am trying to fetch and display new data as I scroll down Every time I scroll down, I fetch the data and save it in Redux. However, due to pagination, only 10 items are shown and not added to th ...

Adjust Fabric js Canvas Size to Fill Entire Screen

Currently, I am working with version 4.3.1 of the Fabric js library and my goal is to adjust the canvas area to fit its parent div #contCanvasLogo. I have tried multiple approaches without success as the canvas continues to resize on its own. Below is the ...

What causes the occurrence of "undefined" after multiple iterations of my code?

I've encountered a curious issue with the code snippet below. Everything seems to be running smoothly except for one thing - after a few iterations, I start getting "undefined" as an output. You can test this for yourself by running the code multiple ...

Steps to showcase a form on a webpage using a button

My webpage features an HTML table with a table navigation bar that allows users to add items or inventory. However, when the "add item" button is clicked, a form appears below the table instead of on top of it. I want the form to display itself right on to ...

I have a quick question: What is the most effective method for creating PDF templates with Angular and .NET 6, specifically for designs that feature heavy

Seeking the optimal solution for creating PDF templates using Angular and .NET 6? Specifically looking to design templates that heavily feature tables. In my exploration of efficient PDF template creation with Angular and .NET 6, I ventured into using pdf ...

Steps to insert a personalized attribute into a TypeScript interface

UPDATED EXPLANATION: I'm fairly new to TypeScript, so please bear with me if this question seems basic. I'm working with an existing library (ngx-logger) that I don't want to or can't modify. My goal is to create a service that generat ...

Is CSS being dynamically generated by style?

I have a website that I need help with: The footer on my site is currently black and I want to remove it To fix this issue, I have to adjust the height in this line of code <div style="position: relative; height: 126px;" id="footer-sidebar" class="fo ...

Use PHP to open a text file and display its contents in a textarea

I have a textarea on my website and I'm trying to figure out how to populate it with the content of a text file. I followed a tutorial that guided me through writing some code, but when I implement it, I'm facing an issue where the words from the ...

Is it accurate to consider all JavaScript code and variables as inherent properties of an execution context?

It's worth considering that everything in JS code can be viewed as a property of an execution context, whether it's a global, function, or eval() execution context. Why is this the case? Each execution context has its own unique lexical and v ...

The functionality of the anchor tag is restricted in both Chrome and Safari browsers

I'm having an issue with HTML anchor tags not working properly in Chrome and Safari. Instead of scrolling up, the page scrolls down when clicked. Here is the HTML code I'm using: <a id="to-top"></a> <a class="button toTop" href="# ...

`Is there a specific location for this code snippet?`

Recently, I stumbled upon a script that enables website screen scraping. For instance, you can check out an example on JsFiddle The issue arises when I attempt to incorporate another script from "Embed.ly" This specific script enhances a provided link and ...

Integrate a character key feature to cycle through options in a customized Vue select component

In my Vue/Nuxt.js project, I have implemented a custom select component with arrow key functionality for scrolling through options and selecting with the enter key. Now, I am trying to add "jump key" functionality where pressing a character key will jump t ...

Check the length of a ngRepeat array after the initial filtering before applying limitTo for further refinement

Currently, I am implementing pagination in my Angular application by using a custom startAtIndex filter along with the limitTo filter. My goal is to show the total number of results in the dataset, regardless of the current page. However, due to the use of ...

Attempting to delete a request using FormData resulted in a 500 error response

Currently, I am working on deleting an attachment by sending a request with form data containing a URL through an API path along with an ID. deleteAttachment(id, url) { const formData = new FormData(); formData.append('url', url); ...

housing the picture within a CSS grid

I am new to working with css grids and I have encountered an issue. The background image I want to use is larger than the size of the grid itself. How can I make the image fit within the grid without exceeding its boundaries? When I attempt to insert the ...

How can I conceal login and register router-links in the Vue + Laravel SPA project navbar immediately after a user logs in?

Currently, I am working on my Bachelor's degree project and have encountered a specific issue. While the login, register, and logout functions all seem to be working well, there is an inconsistency with the navigation bar not automatically switching b ...