简体   繁体   中英

Is there any way where I can remove custom validations in HTML and add alerts?

I am trying to remove custom validations in HTML that occur with "required" attribute in the form. I do want the validations but I want to introduce "alerts" for the inputs.

 <form> <div> <span>Search_word</span> <input type="text" required></input> </div> <div> <span>Frequency</span> <select required> <option disabled selected value></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </div> <div> <button>Search</button> </div> </form>

Even when I am setting alerts with onlick() method on both, they are coming up twice. If I set up alert only on form, then It's not coming up for the dropdown option. And I am not able to figure out how to remove the custom validations. Is there a way I can turn them to alerts?

You can use classes on HTML to listen the event on JavaScript:

HTML:

<form>
  <div>
    <span>Search_word</span>
    <input type="text" class="required"></input>
  </div>

<div>
  <span>Frequency</span>
  <select class="required">
    <option disabled selected value></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
</div>
<div>
  <button id="search">Search</button>
</div>
</form>

JavaScript:

document.getElementById('search').onclick = function changeContent() {

  var requireds = document.getElementsByClassName('required');
  var error = 0;

  for (var i = 0, len = requireds.length; i < len; i++) {
    if (requireds[i].value == "") {
      var error = error + 1;
    }
  }

  if (error > 0){
    if (error == 1) {
      alert("There is a required field to inform");
    } else  {
      alert("There are requireds fields to inform");
    }
  } else {

    // ....

  }
}

EDIT

In order to keep the HTML validation and introduce a alert message, you can use in HTML:

<form>
  <div>
    <span>Search_word</span>
    <input type="text" required oninvalid="this.setCustomValidity('Enter the search word here'); alert('You have to enter a search word');"
  oninput="this.setCustomValidity('')">
  </div>

<div>
  <span>Frequency</span>
  <select class="required" required oninvalid="this.setCustomValidity('Select a frequency'); alert('You have to select a frequency');"
  oninput="this.setCustomValidity('')">
    <option disabled selected value></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>
</div>
<div>
  <button id="search">Search</button>
</div>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM