AngularJS validation for minimum character count prevents character overflow

Encountering an unusual "issue". I've set up a form with a textarea that has both a minlength and maxlength validation.

In addition, there's a straightforward character count displayed:

<textarea ng-trim="false" ng-model="form.text" minlength="20" maxlength="240"></textarea>
<p>{{240 - form.text.length}} left</p>

I'm puzzled as to why the counter only starts functioning once the characters hit the minlength requirement... As I type, the counter stays at 240. Once I reach 20 characters, it suddenly drops to 220... What could be causing this unexpected behavior?

Example on CodePen

Answer №1

When it comes to basic validation directives like ng-minlength, they prevent ngModel from updating until the validation criteria are met. While this behavior is intentional and beneficial in many scenarios, there are cases where it may not be ideal.

To work around this issue while still leveraging ngModel-based validation (including form validity), you can manually define the validation step using $setValidity. This involves removing the ng-minlength attribute and implementing an ng-change callback instead.

Additionally, ensure that your form element has a name and is part of a named form so that you can access the relevant ngModelController.

<form name="formCtrl">
    <textarea ng-trim="false" 
              ng-model="form.text"
              ng-change="checkTextLength()" 
              name="formText">
    </textarea>
    <p>{{240 - form.text.length}} left</p>
</form>

In your controller (assuming you are using only $scope):

  $scope.checkTextLength = function(){
     if($scope.form.text.length < 20){
          $scope.formCtrl.formText.$setValidity('minlength', false);
     } else{
          $scope.formCtrl.formText.$setValidity('minlength', true);
     }

    if($scope.form.text.length > 240){
          $scope.formCtrl.formText.$setValidity('maxlength', false);
     } else{
          $scope.formCtrl.formText.$setValidity('maxlength', true);
     }
  }

I have created a functional example based on your codepen in this link: here. I also added a section in the template to display the validity state.

Answer №2

The reason for this issue may be that angular does not save the internal state of the textarea in its form.text variable until the minlength condition is met. To verify this, you can simply update the inner text of the <p> tag from form.text.length to form.text.

If possible, consider removing the minlength attribute from the textarea and implementing it as a validation step later on. However, make sure to inform the user about this somehow by displaying a label on-screen to keep them informed.

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

What is the best way to locate this particular element on the webpage?

After using the right-click and selecting inspect element, I located the code of the desired element on the webpage: <input type="text" ng-if="!editing" ng-model="item.Price" ng-click="inputFocus()" ts="" required="" placeholder="قیمت :" class="ng- ...

Identify the credit card as either American Express or American Express Corporate

My JavaScript code can successfully detect credit card types, but I have encountered an issue. I am unable to differentiate between American Express and American Express Corporate cards. Is there a way to distinguish them or is it impossible to identify wh ...

ExpressJS encountered an error due to an unsupported MIME type ('text/html') being used as a stylesheet MIME type

Whenever I start my NodeJS server and enter localhost:8080, I encounter the mentioned error while the page is loading. The head section of my index.html file is provided below. It's puzzling to me why this error is happening, considering that my index ...

Tips for enhancing the speed of drawing circles in mouse movement using JS and CANVAS

My current script allows me to draw a circle during mousemove, but it's not as fast as I'd like. Before drawing the circle, I gather the color pixel during mousemove in order to draw a circle on the canvas with the picked color. I came across ...

Take the THREE.js matrix data from an object

I am trying to perform matrix multiplication in Three.js. In my code, I have an Object3D and I managed to retrieve the correct matrix by using console.log like so: console.log(scene.getObjectByName("Pointer").matrix) The output looks something like this: ...

React: Avoid the visible display of conditional rendering component fluctuations

In my current React project, I am developing a page that dynamically displays content based on the user's login status. The state variable "loggedIn" is initially set to null, and within the return statement, there is a ternary operator that determine ...

Choosing just the element that was clicked and added to the DOM

I've been experimenting with JQuery in a web app I'm developing. The app involves dynamically adding elements to the DOM, but I've encountered an issue with click events for these newly added elements. I'm looking for a way to target an ...

How can a Chrome extension transfer an ArrayBuffer or Blob from a content script to the background script without compromising its data type?

In my current script, I am downloading binary data using XHR in the content script and sending it to the background script: let me = this; let xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'arraybuffer'; xhr.onlo ...

Unable to choose multiple options within a selection field

My webgui testing involves the use of selenium, which includes the following method: protected static selectListItems(String id, String value1, String value2, String value3,String value4){ String values = "" if(StringUtils.isNotBlank(value1)) ...

Mongodb will provide the previous collection

router.post('/orders/finish', function(req, res, next) { var order_id = req.body.order_id; var user_id = req.body.user_id; var table_id = ''; var result = []; mongo.connect(url, function(err, db) { assert.equal(null, err); ...

Error: The function .default.auth.signout is not recognized in the REACT and Firebase environment

I've come across several error questions on StackOverflow, but most remain unanswered. The ones that are answered don't seem to solve my issue. I need help debugging this particular error. In my REACT project using Firebase, I'm working on ...

Connect to dynamically generated div on separate page

I am facing an issue with my navigation bar drop down menu that displays event titles fetched from the database. I want users to be able to click on a specific event and have the page scroll to the dynamically generated content for that event. However, it ...

Updating the CSS style of an inner DIV using JavaScript

Can you provide guidance on how to modify the background color using JavaScript for the different styles listed below? i) Internal Style sheet and/or ii) External Style sheet I am currently working with the card deck slide show available at https://githu ...

Determining the number of words in every line within a textarea

I am looking to determine the number of words per line in a textarea. The width of the textarea is variable. Check out this code snippet that calculates the number of rows: http://jsfiddle.net/2tcygj9e/ ...

What are the benefits of keeping JavaScript and HTML separate in web development?

Recently, I came across the concept of Unobtrusive JavaScript while researching best practices in the realm of JavaScript. One particular point that grabbed my attention was the idea of separating functionality (the "behavior layer") from a web page's ...

Validating Angular UI without requiring an input field (validating an expression)

Currently, I am utilizing ui-validate utilities available at https://github.com/angular-ui/ui-validate The issue I am facing involves validating an expression on a form without an input field. To illustrate, consider the following object: $scope.item = ...

Using words instead of symbols to represent logical operators

When coding in C++, I typically prefer using the 'word' operators: not instead of ! and instead of && or instead of || I find it easier to read, especially when negating statements with not. Is there a similar approach possible in ...

How can Codeception/Selenium help in testing the tooltip or customValidity message?

I am trying to implement a feature in my Codeception scenario where I want to validate a form submission with user errors, such as confirming a wrong email address, and display a custom tooltip message in the browser. HTML <form ... > <label ...

Automatically resize ui-select dropdown box to the left side

I've been tasked with incorporating AngularJS ui-select into my project, specifically creating a multiselect dropdown. Currently, the dropdown box automatically adjusts its width based on the length of the longest selectable text, causing it to extend ...

Guide on dynamically displaying a page based on the response from express/mssql middleware

I have developed a full stack application that includes a registration feature which successfully adds data to the database. Now, I am looking for a way to conditionally display the home page based on whether the login credentials are correct. Within my l ...