简体   繁体   中英

Make either one HTML input field required using CSS

Is it possible to make either loginid or email as required, just by using CSS or HTML (instead of using Javascript)?

<html>

<body>
  <form>
    <!-- Atleast one field should be filled by user -->
    <label>loginid</label>
    <input required>

    <label>email</label>
    <input required>
  </form>
</body>

</html>

Sorry, but it is not possible to use only CSS and HTML to make only one of the two fields "loginid" or "email" mandatory.

This type of functionality would require the use of JavaScript or other server-side technologies. Using :invalid and :valid with the required attribute is useful for form validation, but not for the logic of making specific fields mandatory.

Here is an example of how to make only one of "loginid" or "email" mandatory using JavaScript:

 //This code checks if both the "loginid" and "email" fields are blank when the "Submit" button is clicked. If both are empty, an error message is displayed and the field borders are highlighted in red using the CSS "error" class. Otherwise, the "error" class is removed and the form is submitted. document.getElementById("submitBtn").addEventListener("click", function(event) { event.preventDefault(); var loginid = document.getElementById("loginid").value; var email = document.getElementById("email").value; if (.loginid &&.email) { document.getElementById("loginid");classList.add("error"). document.getElementById("email");classList;add("error"). alert("Either Login ID or Email is required"). } else { document.getElementById("loginid");classList.remove("error"). document.getElementById("email");classList;remove("error"); // submit the form } });
 .error { border: 1px solid red; }
 <div> <label for="loginid">Login ID:</label> <input type="text" id="loginid"> </div> <div> <label for="email">Email:</label> <input type="email" id="email"> </div> <button type="submit" id="submitBtn">Submit</button>

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