Error in Angular form validation: Attempting to access property 'name' of an undefined value

Recently, I encountered an issue with my form while implementing Angular validation. The goal was to ensure that the input fields were not left blank by using an if statement.

However, upon testing the form, I received the following error message:

Cannot read property 'name' of undefined

It appears that the code is unable to read the name attribute of an empty <input> tag. The validation function works perfectly when filling in the 'name' field, but not for other fields such as 'rating' and 'reviewText'. My approach involved checking if these fields were filled out using an if statement. Here's a snippet of the HTML and Angular code below:

reviewModal.view.html (abridged version)

<div class="modal-content">
    <div role="alert" ng-show="vm.formError" class="alert alert-danger">{{ vm.formError }}</div>
    <form id="addReview" name="addReview" role="form" ng-submit="vm.onSubmit()" class="form-horizontal">
        <label for"name" class="col-xs-2 col-sm-2 control-label">Name</label>
            <div class="col-xs-10 col-sm-10">
                <input id="name" name="name" ng-model="vm.formData.name" class="form-control">
            </div>
        <button type="submit" class="btn btn-primary">Submit review</button>
    </form>
</div>

reviewModal.controller.js

(function() {

    angular
        .module('loc8rApp')
        .controller('reviewModalCtrl', reviewModalCtrl);

    reviewModalCtrl.$inject = ['$uibModalInstance', 'locationData'];
    function reviewModalCtrl($uibModalInstance, locationData) {
        var vm = this;
        vm.locationData = locationData;

        vm.onSubmit = function() {
            vm.formError = "";
            if(!vm.formData.name || !vm.formData.rating || !vm.formData.reviewText) {
                vm.formError = "All fields required, please try again";
                return false;
            } else {
                console.log(vm.formData);
                return false;
            }

        };

        vm.modal = {
            cancel : function() {
                $uibModalInstance.dismiss('cancel');
            }
        };
    }

})();

locationDetail.controller.js

(function() {

    angular
        .module('loc8rApp')
        .controller('locationDetailCtrl', locationDetailCtrl);

    locationDetailCtrl.$inject = ['$routeParams', '$uibModal', 'loc8rData'];
    function locationDetailCtrl($routeParams, $uibModal, loc8rData) {
        var vm = this;
        vm.locationid = $routeParams.locationid;

        loc8rData.locationById(vm.locationid)
            .success(function(data) {
                vm.data = { location: data };
                vm.pageHeader = {
                    title: vm.data.location.name
                };
            })
            .error(function(e) {
                console.log(e);
            });

        vm.popupReviewForm = function() {
            var modalInstance = $uibModal.open({
                templateUrl: '/reviewModal/reviewModal.view.html',
                controller: 'reviewModalCtrl as vm',
                resolve : {
                    locationData : function() {
                        return {
                            locationid : vm.locationid,
                            locationName : vm.data.location.name
                        };
                    }
                }
            });
        };

    }

})();

Answer №1

In order to access the name property in the HTML, it is necessary for vm.formData to be defined beforehand. Make sure to update the code in reviewModalCtrl to initialize vm.formData:

vm.formData = {};

Answer №2

Instead of validating things in the controller, utilize angular validation in the following manner.

<div class="modal-content">
    <div role="alert" ng-show="addReview.$submitted && addReview.$invalid" class="alert alert-danger">All fields required, please try again</div>
    <form id="addReview" name="addReview" role="form" ng-submit="vm.onSubmit()" class="form-horizontal">
        <label for"name" class="col-xs-2 col-sm-2 control-label">Name</label>
            <div class="col-xs-10 col-sm-10">
                <input id="name" name="name" ng-model="vm.formData.name" class="form-control" required>
            </div>
        <button type="submit" class="btn btn-primary">Submit review</button>
    </form>
</div>

In the text box, I have integrated required and displayed the error message at the top using ng-show="addReview.$invalid"

No code is required on the controller for this validation method.

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

AngularJS is throwing an error claiming that the controller is not defined and is not a function

Struggling to create a basic angular application, every time I attempt it, I encounter this issue and can never find a solution. The content of App.js is as follows: angular.module('Euclid', ['ui.bootstrap', 'ngRo ...

What is the significance of including the *dispatch* variable in the *dependency array* for the useEffect function?

While reviewing the source code of a ReactJS project, I noticed that the dispatch variable is included in the dependency array of the useEffect hook. Typically, I'm familiar with including useState() variables in this context, so I am curious about th ...

unable to fix slideshow glitch after multiple cycles

I've encountered an issue with my custom JavaScript picture scroll. After 3-4 photo changes, the script crashes the page unexpectedly. I'm not sure what is causing this problem! Can someone provide assistance? Below is the code snippet: <di ...

Having Trouble with Updating Variables in AngularJS Service

I am faced with a challenge involving a series of images displayed side by side. My goal is to determine which image has been clicked, retrieve the relevant information, and display it in a modal window. HTML Markup <section class="portfolio-grid ...

Tips for updating a value in a React TextField using handleChange function

After clicking a button, I need to dynamically set a value in this textfield: <TextField fullWidth inputProps={{ maxLength: 75 }} key="nomeSocial" id="outlined-basic" label="Nome Social" name="nomeSocial&qu ...

The data type 'Observable<any>' cannot be assigned to the type 'StoresSummaryResults'. The property 'Data' is not present in the 'Observable<any>' type

As a newcomer to using the Observable with Angular 2, I am facing an issue where my structure is not receiving the results despite being able to validate the response from my REST API. Below is the data class in Typescript that I have: import { RESTResul ...

"Enhancing Error Handling in Express with Node.js Middleware for Parsing

I've been working on developing a middleware to manage errors, but I'm struggling to send the correct format to my frontend. Below, I'll outline my various attempts in the hopes of getting some guidance on this issue. Attempt 1 app.use(fun ...

What is the process for creating a linked TreeNode in the Ant tree design?

After completing a tree design utilizing Ant Design, I encountered an issue where certain nodes within the tree needed to act as links. Despite my attempts to directly assign links, they were not functioning properly. array.map((node) => { if(node.t ...

Is there a way to transform NextJS typescript files into an intermediate machine-readable format without having to build the entire project?

I need to deliver a Next.js project to my client, but I want to modify the TypeScript files so they are not easily readable by humans. The client will then build and deploy these files to their production environment. How can I achieve this? In summary, C ...

Is there a way to automatically update the state in ReactJS whenever new information is added or deleted, without the need to manually refresh the page

I have encountered an issue that I have been trying to resolve on my own without success. It seems that the problem lies in not updating the Lists New state after pushing or deleting from the API. How can I rectify this so that manual page refreshing is no ...

Display various components using a dropdown selection

I am seeking guidance on how to display different components based on the selected option. I am unsure of how to write the code for displaying either component one or two. Can you provide any examples or references that may help? <template> <div ...

Obtain all the selection choices in a dropdown list using Selenium

Although I have come across similar questions, this one is distinct in its simplicity. Unlike other queries that involve iterating over options in a loop, my question revolves around the usage of the getOptions() method mentioned in Selenium documentation. ...

Is it possible to automate the process of constructing a dependency in the package.json file?

Currently, I am using firebaseui and require building it with French localization because the localized versions are not available on npm. In my current package.json file, the dependencies section looks like this: "dependencies": { "firebaseui": "^3.5 ...

Encountering issues accessing the key value 'templateUrl' in Angular6

I have an object in my component.ts file that I need to iterate through in the HTML template using a ui-comp-menu element. menuObject = [{ 'labels': 'Content1', 'templateUrl': 'assets/partials/sample.html ...

Having trouble setting the value in edit mode for Angular's ui-select2 component

<select id="e1" style="width:100%" ui-select2 tabindex="-1" ng-init="GetAllAgent()" ng-model="Agent" ng-options="ctr as ctr.AgentName for ctr in ListAgent track by ctr.AgentId" ng-change="GetSubAgentList(Agent.AgentId)"> <option value=""> < ...

Having trouble configuring Angular-UI Router to work properly with Apache server

My web app is running on my PC through an Apache server, but I'm having issues with the routing provided by ui.route. It seems that the simple state I defined is never being reached. To troubleshoot, I added a wildcard to catch all paths and found th ...

How to toggle between two background colors in a webpage with the click of a button using JavaScript

I need help with a unique website feature. I want to implement a button that cycles between two different background colors (white and black) as well as changes the font color from black to white, and vice versa. My goal is to create a negative version of ...

Retrieve the value of an unmatched ng-pattern field

<div> <input type="text" name="rate" ng-model="rate" ng-pattern="/^[0-9]+(\.[0-9]{0,2})?$/"/> </div> <span class="text-warning control-label"> {{rate}} ...

Can multiple print buttons in different modals be connected to individual divs within their respective modals?

I am currently developing a webpage using the Foundation 5 framework that features a table of information. Each row in the table contains a link that, when clicked, opens a specific modal displaying detailed information related to that row. I want to add a ...

What steps should I take to configure a test environment specifically for conducting tests with selenium and phantomjs?

I am in the process of setting up my environment for headless testing using Selenium and PhantomJS. Getting PhantomJS Ready: To start, I created a folder named c:/phantomjs and downloaded all the necessary PhantomJS script files into it. Next, I set up a ...