Tips on altering the standard message requesting an email address with an @ symbol included

I want to modify the error message displayed when an invalid email is entered, but I am unable to access the source code.

I believe the source code triggers setCustomValidity based on the appearance of the error message. Here is the relevant element:

<input type="email" value="" name="customer[email]" id="email" class="large" size="30">

The only way I can make changes is by using external JavaScript or CSS files.

There are two approaches I'm considering:

Solution 1: Adding inline HTML elements with JavaScript to achieve something like this:

<input type="email" value="" name="customer[email]" class="large" size="30" oninvalid="this.setCustomValidity('Please Enter valid email')" oninput="setCustomValidity('')">

As a newcomer to JS, I'm struggling with implementing HTML in an external JS file.

Solution 2: Calling the oninvalid and setCustomValidity DOM methods in error_message.js like this:

function emailValidity(){
    var myInput = document.getElementByName("customer[email]");
    myInput.oninvalid = function() { 
                (errorMessage) 
            };
    function errorMessage(){
        myInput.setCustomValidity("hey! the email isn't right");
    }
}

However, even after including this file, it still doesn't change the default error message!

Any assistance would be greatly appreciated. Thank you in advance.

Answer №1

It is imperative that you remember to invoke the reportValidity method on the specified element, as failing to do so will result in no action being taken.

Learn more about HTMLObjectElement.setCustomValidity here

function checkValidity(input) {

  var validityStateObj = input.validity;

  console.log(validityStateObj)

  if (validityStateObj.typeMismatch) {
    input.setCustomValidity('This does not appear to be a valid email address!');
    input.reportValidity();
  } else {
    input.setCustomValidity('');
    input.reportValidity();
  }
}

document.querySelector('#email').addEventListener('blur', e =>
  checkValidity(e.target)
)
<input type="email" value="" id="email">

Answer №2

To ensure proper validation, make sure to add event listeners for both the input and invalid events in a similar manner.

const input = document.querySelector('input');
input.oninput = () => input.setCustomValidity('');
input.oninvalid = () => input.setCustomValidity('Please Enter valid email');
<form>
<input type="email" value="" name="customer[email]" class="large" size="30">
</form>

Answer №3

Your previous code encountered issues because it was not enclosed in a form element. A form is essential for checking inputs and displaying error messages when necessary, so I made sure to include that aspect.

Furthermore, there was a mistake with getElementByName instead of getElementsByName, which should be followed by [0] for selecting the specific element.

Additionally, you were attempting to set validity every time the user submitted the form, whereas it only needed to be done once.

Here's an updated version for you to try out:

var myInput = document.getElementsByName("customer[email]")[0];
myInput.oninvalid = function() {
  myInput.setCustomValidity("Hey! the email isn't right")
};
<form>
  <input type="email" name="customer[email]" id="email" class="large" size="30">
  <input type="submit" onsubmit="emailValidity()">
</form>

Answer №4

Here is the solution that worked for me:

customAnswer.js

document.addEventListener("DOMContentLoaded", function(event) {
  // Original text: "Fill out this field."
  var validateElements1 = document.querySelectorAll('input#username, input#password');

  if (validateElements1.length > 0) {    
    for (var x = 0; x < validateElements1.length; x++) {
      validateElements1[x].setAttribute("oninvalid","this.setCustomValidity('Complete este campo.')");
      validateElements1[x].setAttribute("oninput","this.setCustomValidity('')");
    }
  }
});

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 process for submitting data to an API through a ReactJS website?

I am a beginner in both react and APIs, and I have a query regarding posting to an API. My goal is to post the content of my textarea to an API and receive scores based on the text. The issue lies in the fact that the textarea would send something like th ...

What is the best way to retrieve the name of an element or component using JavaScript

I'm currently working on a webpage that includes ASP.NET panels and JavaScript which retrieves all components present on the page: var items = Sys.Application.getComponents(); My goal is to obtain the name/ID of each element stored in the 'item ...

Modify the `<link>` tag using the `onclick` function in JavaScript

I want to switch up the site's style with just a click on an icon <head> <meta charset="utf-8"> <link rel="stylesheet" href="styled.css" id="styles"> </head> Everytime I try to tackle th ...

Add small pieces of content to CKEditor

Is there a way to add "atomic" block content into CKEditor? For instance, I would like to add <h1>Test</h1> right after the letter "B" in the sentence <p>A B C</p>. Currently, when using CKEDITOR.currentInstance.insertHtml('&l ...

Adjusting the view with a sliding tool

I am new to jQuery and want to create a compact plugin for my specific needs. My goal is to develop a simple timeline plugin that looks like the example below: The green bar below contains two small rectangles that can be dragged left or right to zoom in ...

Shifting the form to the bottom right corner

Just starting out with HTML5 and CSS, I've been experimenting with different elements. One project I've been working on is a form: <div id="form1"> <form action="demo_form.asp" autocomplete="on" > Departure City & ...

Styling radio buttons with customized CSS borders

I'm attempting to style some radio buttons with a bold red border, but I'm having trouble getting it to display correctly in the latest versions of Firefox and Chrome. It works fine in IE9/IE8. For each input element that is required on my form, ...

Construct object in JavaScript recursively

My current project involves creating a file structure index using nodeJS. I am utilizing the fs.readir function to iterate through files and it is working smoothly. However, I am facing an issue when it comes to descending into the directory structure and ...

Modify the font style of numbers based on the keyboard language selected by the user

Is it possible to change the font family of numbers in input fields based on the user's keyboard language? For example, if the user is typing in Persian, the numbers should be displayed in a Persian font, and when they switch to an English keyboard, t ...

Having trouble implementing a Font Awesome icon into a submit button programmatically

One way to use a font-awesome icon as button text in HTML is shown below: <button tabindex="4" type="submit" id="submit" class="btn btn-primary btn-lg disabled" onclick="sendemail(); return false;"><i class="fa fa-paper-plane" aria-hidden="true"& ...

`"Error code 404 - Slash command not found" encountered in discord.js version 12.5.3 while attempting to delete slash commands. This issue has been resolved."`

I am currently in the process of revamping a discord.js music bot that I created some time ago. However, I have encountered an issue where I need to delete my slash commands in order to start fresh. Whenever I attempt to use the client.api.application(clie ...

Can I safely refresh the browser during integration test specifications?

We currently have a set of Protractor and Jasmine specs for our AngularJS project. Is it acceptable to use the following code snippet to clean up things between specs: afterAll(function(){ browser.restart(); } Your insights on this matter would be gre ...

Combine two JSON objects which share a common attribute

I am currently working with two JSON feeds. One feed contains the basic information about a course, while the other contains more administrative details. Here is an example to illustrate what I mean. FIRST {"courses": {"course":{"id":"4","title":"Usi ...

during implementation of ng-repeat directive with JSON dataset

When I receive JSON data and attempt to display it using the ng-repeat directive, I encounter an error ng-dupes error <table> <tr ng-repeat="emp in empArr"> <td>{{emp.empcode}}</td> <td>{{emp.empName}}< ...

Flex basis unexpected vertical overflow is not anticipated

I encountered an issue with my code snippet below: export default function Home() { const lists = ["List A", "List B", "List C", "List D"] return ( <div className="flex gap-3"> {lists.m ...

Trouble with jQuery call in an external JavaScript file?

Just starting out with Javascript and JQuery! Currently using MacOSX 10.8, Safari Version 6.0.3 (8536.28.10) I've created a basic HTML page with a form: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xh ...

Update the value of a td element when a select option is changed in another td element within the same table row

I have a table set up as follows: Header1 | Header2 | Header3 | Header 4 | Header 5 Row 1 |<span>Some Text</span> | <select></select> Row 2 Row 3 . . . . Rows generated dynamically. My objecti ...

Error encountered: "Jest error - TypeError: Unable to access property 'preventDefault' because it is undefined."

I encountered an issue while testing the function below, resulting in the error mentioned above. function toggleRecovery = e => { e.preventDefault() this.setState( { recovery: !this.state.recovery }, () => { ...

Closing Browser Tabs with Javascript or jQuery

I've included a div with survey questions that is hidden by default. When the user tries to close the window or navigate away from the page, I want to display the survey div for confirmation instead of using the browser's default confirm box meth ...

Is it possible for a kraken.js backend to manipulate the content of a webpage?

Currently using kraken.js, which is an express.js framework, to construct a localized website. Within the header section, there are 3 language options provided as links. FR | EN | DE My goal is to have the link corresponding to the currently set locale ( ...