<form action="" name="form-1">
<div><label for="">First Name: <input name="first-name" type="text"></label></div>
<div><label for="">Last Name: <input name="last-name" type="text"></label></div>
</form>function validateForm() {
var x = document.forms["form-1"]["first-name"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}Checking if an input is numeric.
// Get the value of the input field with id="numb"
x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}Automatic HTML form validation does not work in Internet Explorer 9 or earlier.
<form action="" method="post">
<input type="text" name="fname" required> <!-- here -->
<input type="submit" value="Submit">
</form>- has the user filled in all required fields?
- has the user entered valid date?
- has the unser entered text in a numeric field?
- HTML Input Attributes
- CSS Pseudo Selectors
- DOM Properties and Methods
- disabled
- max
- min
- pattern
- required
- type
- :disabled
- :invalid
- :optional
- :required
- :valid
- checkValidity()
- setCustomValidity()
<html>
<head></head>
<body>
<input id="my-number" name="my-number" type="number" min="100" max="300" required>
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("my-number");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}
}
</script>
</body>
</html>- validity
- customError
- patternMismatch
- rangeOverflow
- rangeUnderflow
- stepMismatch
- tooLong
- typeMismatch
- valueMissing
- valid
- validationMessage
- willValidate
<input id="id1" type="number" max="100">
<button onclick="myFunction()">OK</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt = "";
if (document.getElementById("id1").validity.rangeOverflow) {
txt = "Value too large";
}
document.getElementById("demo").innerHTML = txt;
}
</script>