To execute a script when the element is invalid in HTML, use the oninvalid attribute.
Example
You can try to run the following code to implement oninvalid attribute.
<!DOCTYPE html> <html> <head> <title>HTML oninvalid attribute</title> </head> <body> <h2>ID</h2> <form action = "/new.php"> <input type = "text" placeholder = "Student ID" name = "sname" oninvalid = "alert('Fill it first!')" required /><br> <input type = "submit" value = "Submit"> </form> </body> </html>