Having issues with your JavaScript validation?

Something seems off, why isn't it functioning properly...

 <script language="JavaScript" type="text/javascript">


//function to validate empty fields

function isEmpty(strfield1, strfield2) {
  //modify field names below based on your form

  strfield1 = document.forms[0].name.value 
  strfield2 = document.forms[0].email.value

  //validate name field

  if (strfield1 == "" || strfield1 == null || !isNaN(strfield1) || strfield1.charAt(0) == ' ') {
    alert( "Name is required.\nPlease fill in and try again.")
    return false;
  }

  //validate EMAIL field 
  if (strfield2 == "" || strfield2 == null || !isNaN(strfield2) || strfield2.charAt(0) == ' ') {
    alert(" Email is required.\nPlease fill in and try again.")
    return false;
  }
  return true;
}


//function to check valid email address

function isValidEmail(strEmail){
  validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
  strEmail = document.forms[0].email.value;

  if (strEmail.search(validRegExp) == -1)  {
    alert('A valid e-mail address is needed.\nPlease correct and retry');
    return false;
  } 
  return true; 
}


//function that validates all functions, called in the onsubmit event handler

function check(form){
  if (isEmpty(form.field1)){
    if (isEmpty(form.field2)){
      if (isValidEmail(form.email)){
        return true;
      }
    }
  }
  return false;
}

</script>

This code doesn't seem to be working as expected. I'm having trouble understanding what's wrong with it, especially since I have included it in my form as well.

<form onsubmit="return check(this);" action="sendquery.php" name="contquery">

Answer №1

Upon first glance: I noticed an abundance of brackets, as pointed out by @FishBasketGordo, so I won't reiterate that

Secondly - you navigate through the field without testing its value

Thirdly: The function is not receiving the correct names

Fourthly - isEmpty returns false when empty, it should actually return true

All those issues have been addressed and fixed

CHECK OUT THE DEMO HERE

The entire page layout has been updated to demonstrate where everything should be placed. It now utilizes unobtrusive event handling on the form

<html>
<head>
<title>Validation</title>
<script type="text/javascript">

// Trim for IE
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
  }
}

// Function to check for empty fields

function isEmpty(objfld) {
  var val = objfld.value;
  if (val.trim() == "" || val == null) {
    alert(objfld.name+" is a mandatory field.\nPlease amend and retry.");
    objfld.focus();
    return true;
  }
  return false;
}

// Function to validate email address format

function isValidEmail(objEmail){
  var validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
  var strEmail = objEmail.value;
  if (strEmail.match(validRegExp)) return true;
  alert('A valid e-mail address is required.\nPlease amend and retry');
  objEmail.focus();  
  return false;
}

// This function performs all validation functions, defined in the onsubmit event handler

function validate(form) {
  if (isEmpty(form.name)) return false;
  if (isEmpty(form.email)) return false;
  return isValidEmail(form.email);
}


window.onload=function() {
  document.getElementById("form1").onsubmit=function() {
    return validate(this);
  }
}

</head>
<body>
<form id="form1">
  Name:<input type="text" name="name" /><br/>
  Email:<input type="text" name="email" /><br/>
  <input type="submit" />
</form>    
</body>
</html>

Answer №2

The primary reason for the malfunction is likely due to syntax errors in the code:

// Syntax error ----v
function check(form)){
    if (isEmpty(form.field1)){
        if (isEmpty(form.field2)){
            if (isValidEmail(form.email)){
                return true;
            }
        }
    }
}
// The return statement should precede the previous closing bracket 
// and the final closing bracket should be removed.
return false;

There appears to be an extra closing parenthesis on the first line, as well as an excess of closing brackets. By utilizing tools such as FireBug or Chrome Developer Tools, these issues can be automatically detected and highlighted.

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

Inquiring about the functionality of vertical and horizontal scrolling in jQuery localscroll

I recently finished building a webpage at . On this page, I have a set of main links along with corresponding sublinks. Currently, clicking on a main link causes the content to scroll vertically, while clicking on a sublink like Blue Inner Link 1 results i ...

JavaScript Function for Finding the Time Difference Between Two Dates (in Years, Days, Hours, or Less than One Hour)

I need to calculate the time difference between 2 dates and display it. If the difference is greater than a year, show the number of years only. If it's more than a day, show the number of days. If it's less than a day, show the number of hours. ...

JS will reach its stopping point at the specified style.zIndex

I am currently in the process of setting up button elements. I have two scripts that correspond to different types of buttons - one script runs a simple collapse menu, while the other executes a more complex collapse by shifting depths and sliding one div ...

Adding a checkbox to menu items in a ReactJS application can be accomplished by utilizing specific components

I have successfully created dynamic menus using a recursive function, and they are displaying in the correct order without any issues. Requirement: My current goal is to identify the last level of menus and assign a checkbox with the value corresponding ...

Tips for sharing a React component with CSS modules that is compatible with both ES Modules and CommonJs for CSS modules integration

Some frameworks, like Gatsby version 3 and above, import CSS modules as ES modules by default: import { class1, class2 } from 'styles.modules.css' // or import * as styles from 'styles.modules.css' However, other projects, such as Crea ...

Show the chosen item from a dropdown menu using Bootstrap

Here is the HTML code that I am working with: <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="h ...

Creating a seamless scrolling experience with a designated stopping point - here's how to achieve it!

I understand how to implement a scroll effect on an element with a specific class or ID. However, I am unsure of how to make the scrolling stop 20px above that element. I have seen examples using document.getElementById() to achieve this: function scr ...

Is There a Workaround for XMLHttpRequest Cannot Load When Using jQuery .load() with Relative Path?

My current project is stored locally, with a specific directory structure that I've simplified for clarity. What I'm aiming to do is include an external HTML file as the contents of a <header> element in my index.html file without manually ...

Confirm the data in each field of a form individually

I am facing an issue with a form that contains 7 fields. When I submit the form to the "register.php" page, it processes each field one by one and outputs the result as a whole. However, I need to validate the data using ajax, collect the output one by one ...

Utilizing square brackets in Node.js for working with URLs

While working in express.js, I encountered an issue when trying to add a router for the URL /xxx/xxx/items[5] that contains square brackets. The router functions correctly without square brackets but fails to work when they are included in the URL. Has a ...

Is it possible to utilize AJAX and JavaScript exclusively for server-side scripting?

Currently in the process of learning PHP, I've decided to analyze the code using a language that I am more comfortable with as my approach. I'm attempting to recreate a PHP dashboard with features such as role management and session logging. Ha ...

The button's background color will vanish if you click anywhere outside the button or on the body of

Struggling with a tabpane created using HTML, CSS, and JavaScript. The problem arises when the background color of the active tab's button disappears upon clicking outside the button or on the body. While switching between tabs, I can change the color ...

Leverage the power of Component Router in conjunction with the Upgrade

While attempting to integrate the Angular 2 Component Router with the upgrade adapter in Angular 2 RC 4, I encountered the following error: Bootstrap at least one component before injecting Router. at setupRouter Below is my main.ts file: angular.mo ...

Trouble viewing Geojson map on website

I'm having trouble generating a map. I am currently working with one of the geojson files provided by The New York Times ("census_tracts_2010.geojson") from this link ( https://github.com/dwillis/nyc-maps ). If someone could take a look at my code be ...

How can I conceal the upload button and still display the names of the files?

I created a user-friendly drag and drop zone for uploading multiple files. Users can simply drag their files into the designated drop area and see the file names displayed there. However, I encountered an issue where hiding the standard "Choose file" butto ...

Emphasize the words within the text box, but wait before doing

I want to create a feature where a single line of text in a <textarea> is highlighted with a time delay. Can I also choose different colors for the highlight? My goal is to have each line turn blue when clicking on individual buttons sequentially. Fo ...

Obtain a transformed mesh that has been displaced using a displacementMap within three.js

Seeking to extract and export the mesh affected by a displacementMap. The displacement of vertexes is determined by this line in the shader (taken from three.js/src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl): transformed += normalize(obje ...

Generate an image instantly from text using ajax when a key is pressed

Currently, I am immersed in a stencil project where my goal is to convert text into an image. In this particular task, there's a textbox that captures the user input on key up event. Once the user enters text, my aim is to display that text as an imag ...

Guide to correcting Form Data errors with XHR resulting in a 400 Bad Request

This is a straightforward piece of code I've written. It's simply a POST request to my API endpoint using FormData. Interestingly, the API is returning a bad request error for reasons unknown to me. When I tested the API with curl, everything wo ...

Steps for dealing with uncaught exceptions in react and displaying a straightforward "internal error" notice on the user interface

When working on the node side, // Handling uncaught exceptions with Node.js process.on('uncaughtException', (error, source) => { fs.writeSync(process.stderr.fd, error, source); }); How can we achieve similar functionality in React for the ...