Encounter a parameter validation error

Just a quick question. I have a JS function that takes a parameter as input. If the passed value happens to be NULL, I want to handle it accordingly. However, my limited experience with JS is making it difficult for me to use the correct syntax. Here's what I have so far. Can you help me change the syntax? The function has more code besides this snippet, and it works fine when I don't check for NULL. The issue lies in the last line due to using a reserved word, but I'm unsure how to resolve it.

<script type="text/javascript">

    //Pass UserName from text box on form to Ajax call 
  function CheckUserName(UserName_element) {

      var UserName = try { UserName_element.value; } catch (e) { };

For those wondering: This is a JavaScript function inside a VBScript Sub (unfortunately, the entire site is built in classic ASP).

    Sub UserNameValidation_Entry()
%>
<div id="username_validation" style="width:15px;position:relative;float:right;">
<img id="valid_UserName_image" src="<%=UrlForAsset("/images/tick.png")%>" border="0" style="display:none;" alt="User Name is Available." 
    title="User Name is Avaliable." />
<img id="invalid_UserName_image" src="<%=UrlForAsset("/images/icon_delete_x_sm.png")%>" border="0" style="display:none;" alt="User Name Already Exists." 
    title="User Name Already Exists." />
</div>

<script type="text/javascript">

        //Pass UserName from text box on form to Ajax call 
      function CheckUserName(UserName_element) {

          var UserName = UserName_element.value; 
          var UserName = try { UserName_element.value; } catch (e) { };


        $j.ajax({
            data: { action: 'CheckUserName', p_UserName: UserName },
            type: 'GET',
            url: 'page_logic/_check_username_ajax.asp',
            success: function (result) {

                //If user exists return X out, if not return green checkmark
                if (result == "True") {
                    try { valid_UserName_image.style.display = "none"; } catch (e) { };
                    try { invalid_UserName_image.style.display = "inline"; } catch (e) { };
                }
                else {
                    try { valid_UserName_image.style.display = "inline"; } catch (e) { };
                    try { invalid_UserName_image.style.display = "none"; } catch (e) { };
                    }
                }
            }
        );
        //return false;
    }
</script>

Here's where the function is called.

           <tr class="required_field">
            <td class="empty"></td>
            <td><b>Username:</b></td>
            <td class="label_value_separator"></td>
            <td>
                <input type='text' name="username" size="24" maxlength="50" value="<%=Session("s_username") %>" onblur="CheckUserName(this);">
                <% Call UserNameValidation_Entry() %>

        </tr>

Answer №1

As mentioned by minitech, there may be no need to utilize a try/catch block in this situation. This is typically only necessary when trying to access an object property that could potentially be "undefined", or when attempting to parse JSON that may not be valid.

A simple solution would be to

if ( username !== null ) {
  // Send AJAX request
} else {
  // Send error message to UI
}

There are various other methods for detecting JavaScript null-like values discussed in this response.

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

Display HTML using JavaScript/jQuery

I am trying to figure out how to print a document by passing custom HTML code. Below is the code I have tried, but unfortunately it's not working: function Clickheretoprint() { var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes, ...

The characteristics of angular js Service/Factory and how they influence functionality

I'm seeking clarification on the behavior of AngularJS, especially in terms of JavaScript. In my code, I have a controller that has an Angular factory injected into it. Here's a snippet from the controller: $scope.localObjCollection = myObjFac ...

What is the reason behind using 'dummy' local variables to define return object keys?

I've come across a code similar to the one below on several occasions recently. One thing to observe is that modelMapper, viewMapper, and source are all defined as local variables but are not used anywhere else, except for being keys in the return ob ...

Contrast between categories and namespaces in TypeScript

Can you clarify the distinction between classes and namespaces in TypeScript? I understand that creating a class with static methods allows for accessing them without instantiating the class, which seems to align with the purpose of namespaces. I am aware ...

adjusting three sections within a flexible navigation bar

Having difficulties creating a dynamic navbar that changes on scroll and keeping the elements within the nav fixed when the menu options appear. For reference, you can check out this codepen: http://codepen.io/timothyfernandez/pen/azXQPV Any assistance w ...

How to style the second child div when hovering over the first child div using makeStyles in Material UI

I am working on a web project with a parent div and two child divs. I need to apply CSS styles to the second child div when hovering over the first child div. Below is the structure of the render method. <div className={classes.parent}> <div c ...

What is the best way to organize an Express application that handles both API requests and views?

Currently, I am in the process of developing a small application that will function as both a website and its API. To achieve this, I am utilizing Node, Express, and Webpack. The structure of my directory is organized as follows: >client |>dist ...

Fixing the mobile display issue with react-responsive-carousel

I am relatively new to ReactJS and I am looking to develop a responsive Carousel. Here is the code snippet that I have currently: To achieve a responsive Carousel for both desktop and mobile devices, I utilized the react-responsive-carousel library. The ...

Saving functions in the localStorage API of HTML5: A step-by-step guide

I have encountered an issue while trying to store an array in local storage using JSON.stringify. The array contains functions (referred to as promises) within an object, but it seems that when I convert the array to a string, the functions are removed. Su ...

Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?

import { HttpHandler, HttpInterceptor, HttpParams, HttpRequest, } from '@angular/common/http'; import { Injectable } from '@core/services/auth.service'; import { exhaustMap, take } from 'rxjs/operators'; import { Authe ...

Incorporating Node.JS variables within an HTML document

After building a simple site using Express, I discovered that Node.js variables can also be used with Jade. exports.index = function(req, res){ res.render('index', { title: 'Express' }); }; This is the code for the index file: ext ...

Tips on creating a post that can be viewed exclusively by one or two specific countries

I'm stumped on how to create a post that is visible only to specific countries. How can I code it to determine the user's country without requiring them to make an account? Any advice or hints would be greatly appreciated. ...

Learn how to access the media.navigator.enabled value of Firefox using Javascript

Lately, I've been working on a demo that utilizes getUserMedia() in Javascript to access the webcam of devices and display the video stream on an HTML5 canvas. In cases where browsers do not support getUserMedia(), I have implemented a fallback to a F ...

The ajax success error function does not trigger in jQuery

Hey, check out my code below: <html> <head> <script src="http://code.jquery.com/jquery-1.8.0.min.js"> </script> </head> <body> <form id="foo"> <label for="bar">A bar</label> <input id ...

Node.js JSON parser encountering an unexpected undefined error

Whenever I attempt to JSON.parse the string, an error occurs and I receive this message: undefined:1 {"device":"FaclonTest","data":[{"tag":"LATITUDE","value":1903.5091},{"tag":"LONGITUDE","value":07251.0348}]} I'm unsure of where the mistake is. Can ...

How to Ensure an Element Appears Above Another Despite Z-Index Troubles?

After conducting approximately 2 hours of research on this topic, I was unable to find clear answers or solutions. Hence, I have decided to address the issue here. The problem I'm facing is as follows: Due to the nature of HTML/CSS, it seems impossi ...

Reproducing scripts in Google Tag Manager and React/Next applications

Currently, I am delving into the realm of Google Tag Manager and React + Next.js for the first time. This experience is proving to be quite intriguing as my familiarity with GTM is limited and my exposure to React is even less. Nonetheless, it's not a ...

Monitoring the sharing of content on social media networks, rather than tracking individual

After setting up a hidden page on my site and configuring buttons to test pushing data to the dataLayer, I have ensured that my Google Tag Manager (gtm) is functioning properly. I recently tracked a Google +1 button click successfully, confirming that my c ...

Purge stored events from BehaviorSubject in Angular2 using Observables as they are consumed

I'm encountering an issue that I believe stems from my limited understanding of Observables. This project is built on Angular2 (v4.0.3) and employs rx/js along with Observables. Within a state service, there exists a store for events: // Observab ...

Utilize JSON data fetched from a URL to dynamically populate an HTML content

There is a JSON file located at a URL that looks like this: [{"tier":"SILVER","leagueName":"Tryndamere's Wizards","queueType":"RANKED_SOLO_5x5","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":18,"wins":411,"losses":430,"rank" ...