Checking the submission text field with Javascript is being confirmed

It seems I've made a small mistake somewhere, and I would appreciate it if someone could help me find it. I'm attempting to validate a postcode in a form field once it's been entered. I've tried similar code in PHP, and it works fine, but no matter what I do, the JavaScript doesn't seem to be executing. Here's part of the form (all within body tags):

<form name ="register" method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">

...

<script  type="text/javascript" src="common.js">
             </script>

<input type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10"  value='' onchange="isValidPostcode(this.form)"  required />

These are versions of the JavaScript function (filled with alerts to print out something).

Version 1:
function isValidPostcode(form) { 
    alert("called");

    var p = document.register.postcode.value;
    var postcodeRegEx = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i'; 

    if (postcodeRegEx.test(p)) alert("OK"); 
    else alert("This does not look like a valid UK postcode...");
}

Version 2:

function isValidPostcode() { 
    alert("called");
    var p = document.getElementById('postcode').value.replace(/\s/g,''); 

    var postcodeRegEx = '/^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i'; 

    if (postcodeRegEx.test(p)) alert("OK"); 
    else alert("This does not look like a valid UK postcode...");
}

I've tried binding to other events, but I can't get a single alert. Even replicating the examples exactly isn't working. I hope someone can help me figure out what's wrong.

Answer №1

It is recommended to use the keyup event instead of onchange and eliminate the quotes from the regular expression pattern :)

<input type="text" name="postcode" class="form-control" placeholder="Postcode" maxlength="10"  value='' onkeyup="isValidPostcode(this.value)"  required />

function isValidPostcode(value) { 
        var postcodeRegEx = /^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i; 
         if (postcodeRegEx.test(value)) console.log("OK"); 
         else console.log("This does not appear to be a valid UK postcode...");
        }

Answer №2

To achieve this, it is recommended to utilize the keyup event in JavaScript rather than adding the event inline.

The variable postcodeRegEx should be treated as a regular expression, meaning the quotes surrounding it need to be removed.

function validatePostalCode() {
    var postalCode = document.getElementById('postcode').value.replace(/\s/g, '');
    
    var postcodeRegEx = /^([g][i][r][0][a][a])$|^((([a-pr-uwyz]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[a-hk-y]{1}([0]|[1-9]\d?))|([a-pr-uwyz]{1}[1-9][a-hjkps-uw]{1})|([a-pr-uwyz]{1}[a-hk-y]{1}[1-9][a-z]{1}))(\d[abd-hjlnp-uw-z]{2})?)$/i;
    
    if (postcodeRegEx.test(postalCode)) {
        alert("Validation successful");
    } else {
        alert("The provided postal code does not appear to be valid for the UK...");
    }
}
document.getElementById("postcode").addEventListener("keyup", function() {
    validatePostalCode();
});
<form name="register" method="post" action="" autocomplete="off">
    <input id="postcode" type="text" name="postcode" class="form-control" placeholder="Postal Code" maxlength="10" value='' required />
</form>

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

Toggle the div's visibility to fade in and out once more

Apologies if this is a simple issue to resolve. My goal is to create a div that, when selected, will be replaced by another div with the option to switch back to the original div when "back" is clicked. This is my current progress: $(document).ready( ...

The code is nearly identical except for one issue that causes an infinite loop within useEffect

Hey, I'm new to reactjs and I've encountered a puzzling situation with the following two code snippets. I can't figure out why using the "First code" results in an infinite loop (endless '123' log outs in my browser console) while ...

Erase a chat for only one user within a messaging application

Currently, I am in the process of building a chat application using nodejs and mongodb. In order to structure my database properly, I have created two models: conversation and messages. Message.js conversationId: { //conversationID }, body: ...

When working with AngularJS, I noticed that the service function within a loop is only executed after all iterations have been completed

Controller Page $scope.page = { '1' : "small", '2' : "large", '3': "medium" }; $scope.form.appraisal_id = "abc123"; $scope.form.user_id = "efg123"; for(var prop in $scope.page ...

Issue: Utilized more hooks than in the previous render cycle

After the initial load of a component that renders and makes data calls on the client side, everything works fine. However, when clicking a "see more" button to make another call, an error occurs in the console indicating that there are too many hooks be ...

Instructions for triggering the opening of a colorbox within an iframe directly on top of the parent window

I am encountering an issue on a page with an iframe. When clicking on a link inside the iframe, it opens a colorbox as expected. However, the colorbox opens within the iframe itself. Is there a way to have the iframe open over the parent window instead? ...

UPDATE: Choosing several classes and then toggling the classes independently for each one

I have managed to make this work, but I am considering if there is a more efficient solution. My objective is to modify the divs using classes exclusively. I aim to toggle 4 classes with just one click. First, I obtain the class for the button and then a ...

Animating SVG fills based on height using JavaScript

I am looking to create an animated gradient effect using JavaScript instead of CSS. I want the gradient animation to change based on the height in both SVG elements. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="200" height="20 ...

Creating a series of images in JavaScript using a for loop

Currently attempting to create an array of images, but with a large number of images I am looking into using a "for loop" for generation. Here is my current code snippet : var images = [ "/images/image0000.png", "/images/image0005.png", "/ima ...

The animation of react-circular-progressbar is experiencing a slight delay of one second

I managed to create a circular progress bar with a timer and a button that adds +10 seconds to the timer. However, I'm facing a 1-second delay in the animation of the progress bar when clicking on the button. If anyone could assist me in resolving t ...

Whenever I use Vue JS, I notice that it displays [Object object] on console.log and returns Undefined when

Currently, I'm developing Vue.JS code to showcase data fetched by PHP from a server. The PHP sends a JSON object to the Vue for display. Below is my existing code snippet: axiosPost(); } function axiosPost() { axios.post( './Conver ...

Ajax and the powerful capabilities of Dojo Ajax offer robust solutions

Recently, I delved into the world of Dojo, a Javascript package that caught my eye. It seems to have its own unique version of Ajax, although from what I can see, it serves similar purposes as standard Ajax. Is there an advantage in using one over the othe ...

Node.js suffering from 'empty post method' issue

I am encountering an issue while retrieving values from certain fields in an index HTML. The post method is returning empty values, with { } being returned instead of the expected email, nick, name, and pass values. Here is my server.js code: var mongoos ...

Choose all elements with a specific class name without the need to specify their position in the list

I'm working on adding a function to my WordPress site that will allow me to show/hide page elements with a specific class. For example, I want any elements (such as rows, containers, and text blocks) that have the 'show-hide' class to be hid ...

The Outer Div Can't Contain Google Maps

I am currently working on integrating a map widget into a dashboard I created using gridstack.js. The sample widget layout that I am aiming for can be seen in the link below: https://i.sstatic.net/ZQP6G.png My goal is to embed the map within the inner (w ...

Is it possible to execute a controller function only when the textarea has completely loaded?

My current setup includes a textarea as shown below: <textarea rows="3" maxlength="144" ng-maxlength="144" type="text" name="testPost" id="testPost_{{item.id}}" ng-init="focusText('testPost', item.id)" ng-model=" ...

Meshes that overlap with transparency features

Could anyone help me with this issue I'm facing? I have a scenario where I am rendering multiple meshes in Three.JS with different solid colors and transparency. However, these meshes are overlapping and the colors are blending together in the overlap ...

Using C# ASP.NET to create an array that corresponds to a JavaScript array

I am trying to figure out how to assign an array in my C# code behind and call a JavaScript function that uses that array. The JavaScript function looks like this: <script type="text/javascript"> var TotalData = new Array(); function S ...

Updating the handler function for AutoComplete with Checkbox in Material UI using React JS

I am looking to include an <AutoComplete /> field in my form. The options for this field are fetched through a get request, and here is the result displayed in the console. [ { "uid": "c34bb0ed-9f63-4803-8639-a42c7e2a8fb0&q ...

Adding a service into a different service within AngularJS

I'm trying to add a login module to my AngularJS app. When I try to call UserService from the authenticationService, it's showing as undefined. What am I missing here, why is UserService coming up as undefined? var authenticationService = angula ...