Home > OS >  How can I hide or show a valiation error in javascript
How can I hide or show a valiation error in javascript

Time:09-28

Im trying to solve a challenge of frontendmentor.io where I have to make a tip calculator. The inputs are ready but I cannot make the validations work.

Someone told me to use aria tags for the hiding and showing the error and pointed me to this page : https://www.a11yproject.com/posts/how-to-write-accessible-forms/

but as the example given I'm not using a submit button. So my question is how do I show or hide my custom error message with the help of javascript.

The code for the input field can be found here :

const money = document.getElementById("amount");
money.addEventListener('blur', (e) => {
  let checked = money.checkValidity();
  console.log(checked);
});
<label for="amount">Bill</label>
<p  id="usernameHint">Invalid input: it need to be an amount</p>
<div >
  <img src="./images/icon-dollar.svg">
  <input type="text" id="amount" value="0" pattern="/(?=.*?\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|\d )?(\.\d{1,2})?$/" />
  <div aria-live="assertive" id="message"></div>
</div>

Invalid input

a

output that I want to see

Invalid input: it need to be a amount

input :

1.00

Output that I want No error message

CodePudding user response:

You have / / in the pattern - remove them

Also checkValidity does not return a value

This will work

const message = document.getElementById("usernameHint");
const money = document.getElementById("amount");
money.addEventListener('blur', (e) => {
  money.checkValidity();
  let checked = money.validationMessage.trim()
  message.hidden = checked === "";
  console.log(checked, money.validationMessage)
});
money.addEventListener('focus', (e) => {
  document.getElementById("usernameHint").hidden = true;
});
<label for="amount">Bill</label>
<p  id="usernameHint" hidden>Invalid input: it need to be an amount</p>
<div >
  <img src="./images/icon-dollar.svg">
  <input type="text" id="amount" value="0" 
  pattern="(?=.*?\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|\d )?(\.\d{1,2})?$" />
  <div aria-live="assertive" id="message"></div>
</div>

CodePudding user response:

If you want to show the message you can use

document.getElementById('yourID').style.display = 'block'";

And to hide it you can do like this

document.getElementById('yourID').style.display = 'none'";
  • Related