Angular JS: Struggling to verify the content of a textarea

Hey there!

I need some help with validating a text area when a link is clicked. The tricky part is that the text area is not inside a form. When a user clicks the link, I want the content entered in the text area to be saved to the database.

I tried writing a validation for this but it's not working as expected. Unfortunately, I'm ending up with blank posts. My aim is to prevent these blank posts from being submitted. I've recreated the form and controller in a fiddle which you can access through the provided link. But before that, please review my HTML and Javascript code below.

HTML

<div ng-app="myApp" ng-controller="myMap">
  <div class="post-textarea" ng-class="{ 'has-error': vm.currentPost.content.$dirty && vm.currentPost.content.$error.required }">
    <textarea class="form-control" rows="3" ng-model="vm.currentPost.content" required></textarea>
    <a ng-click="vm.addPost(vm.currentPost.content,vm.currentPost.$valid)">Click to Post and Validate</a>
  </div>
</div>

Javascript

angular.module('myApp', [])
  .factory('myService', function($http) {
    var baseUrl = 'api/';
    return {
      postCurrentPost: function(newPost) {
        var dataPost = {
          newPost: newPost
        };
        return $http({
          method: 'post',
          url: baseUrl + 'postCurrentPost',
          data: dataPost,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });
      }
    };

  })
  .controller('myMap', function(myService, $http, $scope) {

    var vm = this;
    var userObject;

    // Add a post
    vm.addPost = function(newPost, isValid) {
      if (isValid) {
        var currentPost = vm.currentPost;
        currentPost.content = ""; //clear post textarea
        myService.postCurrentPost(newPost).success(function(data) {
          vm.posts = data;
        });
      } else {
        alert('Validation not working');
      }
    };
    //Check validation
    $scope.getError = function(error, name) {
      if (angular.isDefined(error)) {
        if (error.required && name == 'vm.currentPost.content') {
          return "This field is required";
        }
      }
    }
  });

And here's a FIDDLE.

Answer №1

It is recommended to use the name attribute of form input elements instead of the model value.

Visit AngularJS official documentation for more information.

<div ng-app="myApp" ng-controller="myMap">
    <form name="formContent">
      <div class="post-textarea" ng-class="{ 'has-error': formContent.content.$dirty && formContent.content.$error.required }">
      <textarea name='content' class="form-control" rows="3" ng-model="vm.currentPost.content" required></textarea>
      <a ng-click="vm.addPost(vm.currentPost.content,vm.currentPost.$valid)">Click to Post and validate</a>
      </div>
    </form>
    Content is dirty: {{formContent.content.$dirty}}
    <br>
    Content has required: {{formContent.content.$error.required}}
</div>

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

Achieving multiple validations on a single element in AngularJS, along with the ability to validate

Currently, I am in the process of constructing a form and utilizing the built-in AngularJS validation objects to validate the form. The following is an overview of my form: <form name="myForm" ng-submit="DoSomething()" novalidate> <te ...

Looping through an array in Angular with ng-repeat

In my controller, I have managed to loop through the primary xml-based data successfully. However, I am facing challenges in passing the secondary child data (in the second level tr tag where I want all "list" categories to repeat) within the loop. angula ...

AngularJS version 1.5.11 experiencing issues with ng-repeat functionality

Having an application built on angularJS v1.5.11, I encountered a major issue while attempting to use ng-repeat in a table format like below: <tbody> <tr ng-repeat="score in data.result"> <td ng-repeat="item in score"> {{ item }} & ...

Creating a secure @RestController that encrypts passwords and transmits data in JSON format using Hibernate

When developing a login/registration form in AngularJS and using Spring Boot, I encountered an issue with encrypting passwords into the database. After registering a user, my code for sending data to the database looked like this: @RequestMapping(value = ...

AngularJS $scope variable can be initialized only once using an HTTP GET request

I'm facing an issue with fetching data from an API in a separate AngularJS application. There's a button that triggers the retrieval of data from the API. Upon clicking, it executes the $scope.getApiData function, which is connected to $scope.pr ...

Troubleshooting ng-repeat issues within the MEAN stack framework

I've recently started working with the MEAN stack and was attempting to create a basic contact app, but I'm encountering issues with ng-repeat in my index.html file. Below is my code, following the default file structure provided by Express: ind ...

Issues with launching NPM Start (Having trouble with Node on Mac OS X Yosemite)

As a Rails developer, I decided to expand my skills by learning Angular JS. I came across this tutorial that seemed interesting, but I'm stuck at trying to get a node server to run. Here is the content of the npm-debug.log file: 0 info it worked if ...

What is the recommended way to emphasize an input field that contains validation errors using Trinidad (JSF)?

Trinidad currently displays error messages and highlights labels of failed inputs after client-side form validation. However, I need to directly highlight the input fields themselves. Is there a way to achieve this without resorting to a hack like attach ...

Intentionally introduce discrepancies in the errors during validation of an object using hapi/joi

const validationSchema = Joi.object().keys({ Id: Joi.number().required(), CustomerName: Joi.string() .trim() .required() .when('$isInValidCustomer', { i ...

Sending data that was retrieved asynchronously to a directive

Currently, I am working with an AngularJS controller that retrieves JSON data asynchronously using a $http.get() method and then assigns this data to a scope variable. An overview of the controller code: mapsControllers.controller('interactionsContr ...

The resizing of the window does not occur when a scrollbar is automatically added in IE11

I encountered an issue with my Angular project where the view resizes properly in Chrome and Firefox, but not in IE 11. When the scrollbar appears, some components get covered by the scrollbar. Here is the CSS for the menu: #menu-principal .navbar-lower ...

Updating Angular model remotely without relying solely on the controller

I am struggling to call the addRectangleMethod method from my Javascript code in order to retrieve server-side information into the Angular datamodel. However, I keep encountering an error stating that the method I'm trying to call is undefined. It&ap ...

How to dynamically add variables to object paths using JavaScript and Angular

I've been struggling to grasp this concept, despite hours of searching. My goal is to dynamically generate form fields based on a user-selected 'type' from a dropdown menu. This will be linked to the variable "currentType" in Angular, which ...

New feature alert! Introducing the Mentio JS menu now available at the bottom of the webpage

I am currently working on creating a Twitter-style @mention feature using Angular JS and a library called MentioJS. One issue I encountered is that after dynamically adding content to the page, a mysterious menu appears at the bottom of the page. This pro ...

Anychart remains static when the window is resized

After transitioning my AngularJS application to be built with Webpack, I encountered an issue where all the charts utilizing anychart did not resize when the window was resized. This functionality worked perfectly before I migrated to Webpack from using th ...

Typescript Angular filters stop functioning properly post minification

I developed an angular filter using TypeScript that was functioning properly until I decided to minify the source code. Below is the original filter: module App.Test { export interface IGroupingFilter extends ng.IFilterService { (name:"group ...

Exploring the Functionality of Spring Boot GUI with Selenium WebDriver Testing

After developing a Spring Boot / Angular JS app, I am now looking to implement GUI interface tests. I decided to utilize the Selenium ChromeDriver, so I included the Selenium dependency : <dependency> <groupId>org.seleniumhq.selenium</ ...

Can an element be dynamically bound and unbound upon clicking a button in AngularJS?

After creating a display text and an input field, I bound them together using ng-model in the code below: HTML <div ng-app ng-controller="test"> <div ng-bind="content"></div> <input id="txtElem" type="text" ng-model="content" ...

Example of fetching Pubnub history using AngularJS

I am not a paid PubNub user. I am utilizing the example code for an Angular JS basic chat application from PubNub, and I want to access the chat history. This specific example can be found on the PubNub website. git clone https://github.com/stephenlb/an ...

How can you determine if a user has selected "Leave" from a JavaScript onbeforeunload dialog box?

I am currently working on an AngularJS application. Within this app, I have implemented code that prompts the user to confirm if they truly want to exit the application: window.addEventListener('beforeunload', function (e) { e.preventDefault ...