setCustomValidity()
仅在单击提交禁止后才有效。如何在字段中输入无效输入时使其工作。注意:正确的输入格式为“A1111-11111-11111”,不包括引号。下面是我到目前为止编写的代码。
<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>