JavaScript oninvalid Event: Handling Invalid Input

The oninvalid event in JavaScript is a crucial tool for enhancing user experience in web forms. It is triggered when an input element, such as a text field or select box, fails to meet its defined validation criteria. This event allows developers to provide immediate, contextual feedback to users, guiding them toward correcting errors and ensuring the submission of valid data. Understanding how to effectively use the oninvalid event can significantly improve the usability and reliability of web forms.

What is the oninvalid Event?

The oninvalid event is a standard HTML event that fires when an input field in a form does not pass its validation rules. This can happen due to a number of factors:

  • A field is marked as required, but it’s left empty.
  • An input’s value doesn’t match the expected type, such as entering text in an email field.
  • The value does not satisfy the defined pattern using the pattern attribute.

When an oninvalid event is triggered, it provides an opportunity for developers to:

  • Display custom error messages tailored to specific validation failures.
  • Highlight the problematic input field for better user guidance.
  • Prevent form submission until all errors are resolved.

Syntax of the oninvalid Event

The oninvalid event can be used directly within HTML elements or through JavaScript event listeners.

HTML Attribute Syntax:

<input type="text" oninvalid="javascript_code" />

JavaScript Event Listener Syntax:

element.oninvalid = function() {
  // JavaScript code
};

element.addEventListener('invalid', function(event) {
  // JavaScript code
});
Property Description
`oninvalid` An event handler attribute directly set in HTML tags or set as a property in javascript.
`addEventListener(‘invalid’, function(event){})` The method used to add an event listener that waits for the invalid event to occur.
`event` The event object of type `Event`, containing useful properties such as `event.target`.

Note: While both methods are valid, using addEventListener is generally preferred for its flexibility and ability to manage multiple event handlers. 💡

Basic Examples of the oninvalid Event

Let’s explore some practical examples of how to use the oninvalid event. Each example will include the necessary HTML and JavaScript code.

Basic oninvalid Event with Alert

Here, we’ll set up a basic example that triggers an alert when an input is invalid.

<form id="formBasicAlert">
  <input type="text" id="inputBasicAlert" required placeholder="Required Field" />
  <button type="submit">Submit</button>
</form>

<script>
  const inputBasicAlert = document.getElementById('inputBasicAlert');

  inputBasicAlert.oninvalid = function(event) {
    event.target.setCustomValidity('This field is required!');
    alert('Please fill the required field.');
  };
</script>

In the above example, the inputBasicAlert is required. When you submit the form without entering anything in the field, it shows an alert box saying “Please fill the required field.”

Custom Validity Message

This example shows how to use setCustomValidity() to display a customized message.

<form id="formCustomValidity">
  <input type="email" id="inputCustomValidity" required placeholder="Enter Email" />
  <button type="submit">Submit</button>
</form>

<script>
  const inputCustomValidity = document.getElementById('inputCustomValidity');
  inputCustomValidity.oninvalid = function(event) {
    event.target.setCustomValidity('Please enter a valid email address.');
    event.preventDefault();
  };
  inputCustomValidity.oninput = function(){
      inputCustomValidity.setCustomValidity('');
  }
</script>

Here, if you enter an invalid email address and submit the form it shows a browser-specific message box “Please enter a valid email address.” Also notice how oninput is used to clear the custom validity message when the user start to type in the field.

Using addEventListener

This example uses addEventListener to manage the event.

<form id="formEventListener">
  <input
    type="text"
    id="inputEventListener"
    pattern="[A-Za-z]+"
    required
    placeholder="Only letters"
  />
  <button type="submit">Submit</button>
</form>

<script>
  const inputEventListener = document.getElementById('inputEventListener');
  inputEventListener.addEventListener('invalid', function(event) {
    event.target.setCustomValidity('Please enter only letters.');
    event.preventDefault();
  });
  inputEventListener.oninput = function(){
      inputEventListener.setCustomValidity('');
  }
</script>

In this case if you enter any number or special character then the browser shows a specific message for invalid form which is set using setCustomValidity method in the invalid event. Like the previous example oninput is used to clear the message on input.

Showing Error Message in the Page

This example displays the error message within the page near the input box.

<form id="formInlineError">
  <input type="text" id="inputInlineError" required placeholder="Required Field" />
  <span id="errorSpan" style="color: red; margin-left: 5px;"></span>
  <button type="submit">Submit</button>
</form>

<script>
    const inputInlineError = document.getElementById('inputInlineError');
    const errorSpan = document.getElementById('errorSpan');

    inputInlineError.addEventListener('invalid', function(event) {
        errorSpan.textContent = 'This field is required!';
        event.preventDefault();
    });
  inputInlineError.oninput = function(){
       errorSpan.textContent = '';
    }
</script>

In this case, the error message “This field is required!” is displayed inside a span right next to the input.

Advanced Techniques with oninvalid

Dynamically Changing Error Messages

You can dynamically modify the error message based on different validation failures.

<form id="formDynamicError">
  <input
    type="text"
    id="inputDynamicError"
    required
    pattern="^[a-zA-Z0-9]+$"
    placeholder="Alphanumeric Only"
  />
    <span id="errorSpanDynamic" style="color: red; margin-left: 5px;"></span>
  <button type="submit">Submit</button>
</form>

<script>
  const inputDynamicError = document.getElementById('inputDynamicError');
  const errorSpanDynamic = document.getElementById('errorSpanDynamic');

  inputDynamicError.addEventListener('invalid', function(event) {
    if (inputDynamicError.validity.valueMissing) {
      errorSpanDynamic.textContent = 'This field is required!';
    } else if (inputDynamicError.validity.patternMismatch) {
      errorSpanDynamic.textContent = 'Please enter only alphanumeric characters.';
    }
        event.preventDefault();
  });
    inputDynamicError.oninput = function(){
      errorSpanDynamic.textContent = '';
  }
</script>

Here the message changes depending on the cause of invalid event and uses input’s validity property. The valueMissing and patternMismatch are checked and corresponding error message is displayed.

Highlighting Invalid Fields

Visually highlight the invalid field by adding a CSS class.

<style>
.invalid-input {
  border: 2px solid red;
}
</style>
<form id="formHighlightError">
  <input
    type="number"
    id="inputHighlightError"
    required
    placeholder="Enter a Number"
  />
  <button type="submit">Submit</button>
</form>

<script>
  const inputHighlightError = document.getElementById('inputHighlightError');

  inputHighlightError.addEventListener('invalid', function(event) {
    inputHighlightError.classList.add('invalid-input');
     event.preventDefault();
  });
    inputHighlightError.oninput = function(){
     inputHighlightError.classList.remove('invalid-input');
  }
</script>

In this example, when you try to submit the form without filling the input box or enter any non-number value, the input border is changed to red. Also on input the border will return to its original state by using the oninput event.

Preventing Form Submission

This example shows how to prevent the default form submission using preventDefault().

<form id="formPreventSubmit">
  <input type="text" id="inputPreventSubmit" required placeholder="Required Field" />
  <button type="submit">Submit</button>
</form>

<script>
  const inputPreventSubmit = document.getElementById('inputPreventSubmit');

  inputPreventSubmit.addEventListener('invalid', function(event) {
      event.preventDefault(); // Prevents the form submission.
    inputPreventSubmit.setCustomValidity("Please fill out the required field!");
  });
   inputPreventSubmit.oninput = function(){
        inputPreventSubmit.setCustomValidity('');
  }
</script>

In this example the form is not submitted when the input is invalid due to the usage of preventDefault().

Real-World Applications

The oninvalid event is essential for:

  • User-Friendly Forms: Providing immediate and relevant error feedback improves usability.
  • Data Quality: Ensuring that the submitted data meets the required validation criteria.
  • Accessibility: Enhancing form accessibility by clearly identifying and communicating errors.
  • Custom Validation: Implementing complex validation logic that goes beyond standard HTML attributes.

Best Practices

  • Provide Clear Messages: Inform users exactly what is wrong and how to fix it.
  • Use Visual Cues: Highlight the invalid field using CSS.
  • Use preventDefault(): Prevent form submission until all errors are resolved.
  • Clear Messages on Input: Clear error messages and visual cues when the user starts correcting the input using oninput event.
  • Test Thoroughly: Always test your forms with different types of invalid input.

Browser Support

The oninvalid event is widely supported across all modern browsers, ensuring compatibility across various platforms.

Note: Always test your implementation across different browsers to ensure consistent behavior and a good user experience. 🧐

Conclusion

The oninvalid event is an essential component in building robust and user-friendly web forms. By providing real-time feedback, developers can guide users through form completion, reducing errors and enhancing the overall experience. Mastering the use of the oninvalid event, combined with custom validation and visual cues, allows for the creation of highly interactive and accessible web applications. Happy coding!