1

The setCustomValidity() works only after clicking submit buttion. How to make it work when an invalid input is entered in the field. NOTE: CORRECT INPUT FORMAT IS "A1111-11111-11111" excluding quotes. Below is the code I have written so far.

<html>
<script type="text/javascript">
function validateForm(e){

    var x = document.forms["licenseForm"]["license"].value;
    if(window.event)
     var charCode = window.event.keyCode;
    else if(e)
     var charCode = e.which;
    else
     return true;
 if(x == null || x==""){  
     if(charCode > 96 && charCode < 123)
      return true;
     else if(charCode > 64 && charCode < 91)
      return true;
     else
      return false;
    }
 else if(x.length == 5 || x.length == 11){
     if(charCode != 45)
      return false;
     else
      return true;
 }
    else {
     if(charCode > 31 && (charCode < 48 || charCode > 57))
   return false;
     else
   return true;
 }
}
</script>
<form name="licenseForm" action="" method="post">
    <input type="text" name="license" maxlength="17" onkeypress="return validateForm(event);" oninvalid="this.setCustomValidity('Please enter in the specified format A1111-11111-11111');" pattern=".{17,}" oninput="setCustomValidity('')" placeholder="XXXXX-XXXXX-XXXXX" required/>
    <input type="submit" value="submit"/>
</form>
</html>
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
RAJESHINDIN
  • 171
  • 1
  • 3
  • 16
  • A1111. First letter should be alphabet and latter are digits with two hyphens in the middle. – RAJESHINDIN Sep 23 '15 at 07:18
  • Try using this. Its not same as yours. But it might help http://stackoverflow.com/a/18221081/5026766 – Salman Sep 23 '15 at 07:21
  • 1
    AFAIK the browser validation error message bubbles are triggered by attempting to submit the form. This SO question discusses this: http://stackoverflow.com/questions/12785347/how-to-show-setcustomvalidity-message-tooltip-without-submit-event – Ian Gilroy Sep 23 '15 at 07:54

0 Answers0