Javascript text validation is malfunctioning as the alert message fails to appear

Looking for a simple form validation script:

<script language=”javascript”>
    function checkForm(register) {      
if (""==document.forms.register.FNAME.value){
    alert("Please fill out this field!");
    document.forms.register.FNAME.focus();
    return false;
}    
if (""==document.forms.register.LNAME.value){
    alert("Please fill out this field!");
    document.forms.register.LNAME.focus();
    return false;
}
if (EMAIL.value.search( /^[a-zA-Z]+([_\.-]?[a-zA-Z0-9]+)*@[a-zA-Z0-9]+([\.-]?[a-zA-Z0-9]+)*(\.[a-zA-Z]{2,4})+$/ ) == -1){
    alert(“Invalid email”);
    return false;
}       
if('0'==document.forms.register.GENDER.value){
    alert("Please select an option!");
    document.forms.register.GENDER.focus();
    return false;
}
if (""==document.forms.register.ADDRESS.value){
    alert("Please fill out this field!");
    document.forms.register.ADDRESS.focus();
    return false;
}
if (""==document.forms.register.CONTACTNO.value){
    alert("Please fill out this field!");
    document.forms.register.CONTACTNO.focus();
    return false;
}
}
</script>

Using the onSubmit handler to call the function, but nothing is happening when submit is clicked. It's skipping javascript and going straight to the PHP script. Any ideas why?

Form HTML:

 <form name="register" action="register.php" method="POST" onsubmit="return checkForm(register);">
<table width="100%" border="0">
<tr>
  <td width="46%" height="24" align="right">First Name:</td>
  <td width="54%"><input name="FNAME" type="text" size"20" /></td>
</tr>
<tr>
  <td height="24" align="right">Last Name:</td>
  <td><input name="LNAME" type="text" size"20" /></td>
</tr>
<tr>
  <td height="24" align="right">Email Address</td>
  <td><input name="EMAIL" type="text" size"20" /></td>
</tr>
<tr>
  <td height="24" align="right">Gender:</td>
  <td><select name="GENDER">
      <option value="" selected="selected">- Select One -</option>
      <option value="Male">Male</option>
      <option value="Female">Female</option></select></td>
</tr>
<tr>
  <td height="24" align="right">Address:</td>
  <td><input name="ADDRESS" type="text" size"20" /></td>
</tr>
    <tr>
  <td height="24" align="right">Contact No.:</td>
  <td><input name="CONTACTNO" type="text" size"20" /></td>
</tr>
<tr>
  <td height="24" align="right">Password</td>
  <td><input name="PASSWORD" type="password" size"20" /></td>
</tr>
 <tr>
  <td height="24" align="right">Re-type Password</td>
  <td><input name="PASSWORD2" type="password" size"20" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input name="submit" type="submit" value="Register" /></td>
</tr>
</table>

</form>

Not seeing the alert message? What could be causing this issue?

Answer №1

After reviewing your code, I made some improvements to enhance its logic and maintainability.

Here is the updated HTML snippet:

<form name="register" action="register.php" method="POST" onsubmit="return validate_form();">

Take a look at the updated JavaScript function:

function validate_form() {
    var form = document.forms.register;
    function focus_and_false(element) {
        element.focus();
        return false;
    }
    if (form.FNAME.value === "") {
        alert("Please fill out this field!");
        return focus_and_false(form.FNAME); 
    }
    return true;
}​

Click here for a live example

Answer №2

Your javascript code has a major syntax error that needs to be fixed...

function return validate_form(register)

should be

function validate_form(register)

Try starting with this fix :)

Also, make sure to add an alert right after the function declaration to confirm it is being executed correctly.

Another mistake in your code:

<script language=”javascript”>

Should be

<script type="text/javascript">

Lastly, I recommend changing the function name to

function validateForm(register)

Let me know if this resolves the issue for you :)

Answer №3

Be mindful of using curly quotes in your code

alert(“Wrong email”);  <---bad quotes

It's important not to just use a name

onsubmit="return validate_form(register);"

Instead, pass in "this" which refers to the current scope, in this case, the form element.

onsubmit="return validate_form(this);"

Have you checked the value of EMAIL?

EMAIL.value

Avoid solely referencing element names in your code.

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

Utilize the split functionality only when the character you want to split by is found in

Consider the following situation: I have 6 string variables that contain special characters. I stored these 6 strings in an array like this: arr=[str1,str2,str3...); arr=escape(arr); due to the presence of special characters in some string variables. ...

Adding HTML elements to a button using an array: a step-by-step guide

In the process of developing a web application feature using JavaScript, I have come up with a simple plan: Place a button in the bottom left corner. The button should only become visible after scrolling begins. Upon clicking the button, a new window wil ...

Is there a way to integrate a calendar feature within an Angular 2 application?

I am brand new to Angular 2 and have a question: I need to integrate a calendar into a page where users can add events. Something similar to the following example: I'm unsure if the angular material calendar project is designed for Angular 2 or for ...

Using Ajax to submit two forms by clicking a submit button

Explanation : In this particular scenario, I am facing a challenge where I need to trigger another Ajax function upon successful data retrieval, but unfortunately, I am encountering some unknown obstacles. Code: ---HTML Form : <form accept-charset=" ...

What is the most efficient way to transfer form data from one JSP page to another?

I need to transfer information from one webpage (1.jsp) to another webpage (2.jsp). The data that needs to be transferred includes checkboxes, radio buttons, and drop downs. This data will be used in 2.jsp to generate the appropriate page. Is there a way ...

Custom sample rate options in RecordRTC allow for the recording of silent audio tracks

I am currently working on implementing RecordRTC.js to capture audio from a microphone and then upload it to a server built with nancyfx. Initially, I am simply aiming to upload the audio stream and store it in a wav file for testing purposes. However, my ...

The @Input() function is failing to display or fetch the latest value that was passed

I am currently working on an angular project, and I've encountered a situation where I'm attempting to send a value from a parent component to a child component using the @Input() decorator. Despite my efforts, the child component continues to di ...

Set a timeout for a single asynchronous request

Is there a way to implement a setTimeout for only one asynchronous call? I need to set a timeout before calling the GetData function from the dataservice, but it should be specific to only one asynchronous call. Any suggestions? Thank you. #html code < ...

Having trouble aligning a div in the middle of a slick-slider item using flex styling

I've created a slick slider component in Vue, and I'm facing an issue with centering a circular div inside each of the slider items. Despite trying to align and justify center along with adding margin:auto for horizontal centering, I can't s ...

How can I update the state with the value of a grouped TextField in React?

Currently working on a website using React, I have created a component with grouped Textfields. However, I am facing difficulty in setting the value of these Textfields to the state object. The required format for the state should be: state:{products:[{},{ ...

Developing with node and express: optimizing your workflow

After researching various blogs and tutorials on node + express development workflow, there is one crucial aspect that seems to be missing: When developing, which version of the app should you have open in your browser? The source app, featuring clean, ...

CORS request results in unsuccessful cookie setting in browsers except for Firefox where Set-Cookie header is detected; notably, Chrome does not show the header

I'm experiencing an issue with setting cookies from a NodeJS server to the client using JQuery and AJAX. Despite seeing the Set-Cookie headers in the response, the cookies are not showing up in the document.cookie string. I would greatly appreciate it ...

I am unable to utilize the backspace function within a text box generated by JavaScript

I have created a dynamic form using JavaScript that includes buttons and one text input field. However, the issue is that to delete the text entered in the input field, one must highlight the text and then type over it instead of being able to simply use t ...

Disabling related videos in React Native: A guide to preventing suggested content from appearing at the end of YouTube videos

Is there a way to turn off the display of related videos after a YouTube video ends in react native? I've tried the following code, but it doesn't seem to be working: state = { isPlaying: true, related :false, }; <YouTube apiKe ...

Parcel-Bundler is unable to resolve critical security issues

I recently followed a tutorial by Kevin Powell on SASS and Parcel through YouTube. I was able to successfully set up the SASS part and get the Parcel bundler working smoothly on one project, so everything seemed to be going well at that point. However, to ...

Lock the initial column in an HTML table

Hey there! I've been trying to freeze the first column of my HTML table, and while I managed to do so after a few attempts, I encountered an issue. When I scroll the table horizontally, the columns on the left seem to overlap with the first column, an ...

Navigating the complexities of extracting and storing a data type from a collection of objects

Dealing with a messy API that returns inconsistent values is quite challenging. Instead of manually creating types for each entry, I am looking for a way to infer the types programmatically. One approach could be by analyzing an array like this: const arr ...

JavaScript error: Function is not defined when using Paper.js

UPDATE the problem has been solved by making the colorChange function global I am attempting to modify the color of the path when the 'Red' button is clicked using the colorChange function. Despite my efforts, I keep getting an error stating tha ...

The URL in an AJAX request includes a repeating fragment due to a variable being passed within it

const templatePath = envVars.rootTemplateFolder + $(this).attr('link'); console.log("templatePath : ", templatePath); $.ajax({ method: "GET", url: templatePath, context: this, success : function(result){ ...

Filtering elements using two dropdown lists

In my list, each li element has data-name and data-body attributes. I want to display only the li elements that match the selected values. The first select option is for selecting the car name, while the second select option is for selecting the car body. ...