Issue with dynamically filling a form field using ValidityState

I have been utilizing the ValidityState interface for client-side form validation, but I've encountered an issue. Whenever my form is populated programmatically, such as after making a call to a third-party API, the tooLong state always returns false, even when the field length exceeds the limit.

To demonstrate this problem, I have created a simple mocked code example:

document.querySelector('form').setAttribute('novalidate', true);

const input = document.getElementById("test");
input.value = "inputstringtoolonga";

console.log(input.validity);
.field {
  max-width: 410px;
  margin-bottom: 15px;
}
<div class="d-flex">
    <form class="validate" autocomplete="off">
      <div class="field">
        <input placeholder="Test" type="text" maxlength="6" class="form-control" id="test" pattern="^[0-9]+$" required>
      </div>
      <button type="submit" class="btn btn-primary" disabled>Submit</button>
    </form>
</div>

While the patternMismatch state functions correctly when the pattern is not matched, the tooLong state remains false regardless of actually exceeding the maxlength attribute set for the input field. This discrepancy is evident in the provided example.

It is clear from the demonstration that the input value surpasses the specified maxlength attribute. However, the tooLong state does not reflect this violation. What could be causing this inconsistency?

Answer №1

As per the information provided on MDN's website

When it comes to input fields, if the length of the text value exceeds maxlength UTF-16 code units, constraint validation will fail. This validation is triggered only when the user makes changes to the value.

It is worth noting that this constraint does not apply when values are assigned programmatically.

In certain browsers like Chrome, maxlength is implemented interactively, preventing users from entering more characters than allowed in the input field. However, this restriction does not apply when values are being assigned.

If you want to enforce this constraint even for assigned values, consider adjusting your pattern attribute. You can modify it from:

pattern="^[0-9]+$"

to:

pattern="[0-9]{1,6}"

(Keep in mind that you do not need to include the ^ and $ anchors, as they are automatically assumed within the pattern.)

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

Executing a function on each page within the head tag in Nuxt.js

I successfully made my function accessible by using the plugin attribute in the nuxt.config.js file, allowing me to call the function under mounted on every page. I am looking for a more efficient way to run this function within the head tag and have it b ...

Incorporating Material-UI with React Searchkit for a seamless user experience, featuring

I encountered an issue when trying to use both searchkit and material-ui in my React application. The problem arises from the fact that these two libraries require different versions of reactjs. Initially, everything was working fine with just searchkit in ...

Is there a way to create a universal script that works for all modal windows?

I have a dozen images on the page, each opening a modal when clicked. Currently, I've created a separate script for each modal. How can I consolidate these scripts into one for all modals? <!-- 1 Modal--> <div class="gallery_product col-lg-3 ...

Is it possible to utilize npm packages within a standard web page without any frameworks or libraries?

I am currently working on a basic website created using vanilla HTML, CSS, and JS files. My goal is to incorporate the import { moment } from "moment" syntax into my JS files. However, after adding npm to my project, installing moment with npm i ...

The present user who is currently logged into the stackmob platform

I am currently working on retrieving a list of contacts for the logged-in user, but I am struggling to identify the current user. In Parse.com, you would use Parse.User.current(), but I am unsure if Stackmob offers a similar functionality. Below is the co ...

JavaScript's includes method fails to verify input against the array

Just starting out with Javascript and striving to write clean code! To test my app, I aim to have a user's name input via prompt checked against an array for validation purposes. When I hardcode the value of a variable, the includes function filters ...

Unable to transfer Vue.js components in and out of the project

I have a directory structured like this. VueTree components Classic.vue Modern.vue index.js The Classic and Modern components consist of a template, export default {}, and a style. I am importing both of them in index.js as: import Classic ...

v-for triggers actions on every div

Yesterday I posed a question regarding the removal of a custom truncate filter in Vue. If you missed it, you can find the original question here: Deleting a Vue custom filter when mousing over However, what I failed to mention is that I am utilizing a v- ...

What is the best way to transform a GET request with a query string into a promise?

After successfully making a request with querystring params, I encountered an issue while trying to promisify my request: // Works var Promise = require("bluebird"); var request = Promise.promisifyAll(require("request")); request.get({ url: 'htt ...

Consistentize Column Titles in Uploaded Excel Spreadsheet

I have a friend who takes customer orders, and these customers are required to submit an excel sheet with specific fields such as item, description, brand, quantity, etc. However, the challenge arises when these sheets do not consistently use the same colu ...

Expanding properties in a React component based on certain conditions using TypeScript

I am attempting to dynamically expand my component props based on whether a specific prop is included. The goal is to add attributes from an anchor if the href prop is provided, and include attributes from a button if it is not. Is this achievable? Chec ...

Transfer the information on the onClick event to the loop's function

When creating my component within the parent component, I follow this approach: renderRow(row){ var Buttons = new Array(this.props.w) for (var i = 0; i < this.props.w; i++) { var thisButton=<FieldButton handler={this.actionFunction} key={&ap ...

Tips for structuring an object map with flow type to ensure that each value includes a corresponding key

In an attempt to correctly type (using Flow) a helper function called createReducer for Redux, I have utilized the code from redux-immutablejs as my starting point. I am following the recommendations from the flow documentation on typing Redux reducers, b ...

Tips for utilizing the loadDataWithBaseURL() method to load CSS and JS files directly from an SDCARD

I am facing an issue with loading files from SDCARD onto a webview. The .html, .js, .css files are stored on the SDCARD in my scenario, and the html file content is encrypted. The steps I follow to load the html file are: Read file content Decrypt all co ...

Utilizing window.location.pathname in Next.js for precise targeting

Are you familiar with targeting window.location.pathname in NEXT.JS? I encountered a red error while using this code in Next.js const path = window.location.pathname console.log(path) // I am able to retrieve the pathname here Then { ...

Modify all the content within the DIV using Regex, while keeping the HTML tags intact

I am attempting to replace all the text inside a DIV, including within its children, without modifying any HTML tags. Specifically, I want to switch all instances of 'Hello' to 'Hi'. Thank you for your help. var changes = $('div ...

Unable to initiate the server in a new window due to the absence of a specified terminal application

When incorporating an external library into my React Native project, the installation process is usually smooth. However, when I try to integrate the library into my entire project and run 'react-native run-android' command, it shows an error. I ...

"The error message "Node JS, MYSQL connection.query is not a valid method" indicates

db_config.js: const mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'test' }) connection.connect(function(err) ...

Unable to make a request to the localhost node server via fetch API from an HTML page

Description: I am attempting to transmit JSON data from an HTML page to a Node.js server running locally on port 5000 using the Fetch API. Error Encountered: The request to 'http://localhost:5000/attend' from origin 'http://127.0.0.1:5501 ...

having difficulty altering a string in EJS

After passing a JSON string to my EJS page, I noticed that it displays the string with inverted commas. To resolve this issue, I am looking for a way to eliminate the inverted comma's and convert the string to UPPERCASE. Does anyone know how to achiev ...