JavaScript Validation

Back to JS page

Table of Contents

JavaScript Form Validation

HTML form validation can be done by JavaScript.

If a form field (fname) is empty, the required attribute prevents form submission:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Validation</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Form Validation</h4>
<form action="/action_page.php" method="post">
  <label for="fname">First name:</label>
  <input type="text" id="fname" name="fname" required>
  <input type="submit" value="Submit">
</form>

</body>
</html>

Example 1

Result View Example

JavaScript Can Validate Numeric Input

JavaScript is often used to validate numeric input:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Validation</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Validate Numeric Input</h4>
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>

<script>
function myFunction() {
  let x = document.getElementById("numb").value;
  let text;
  if (isNaN(x) || x < 1 || x > 10) {
    text = "Input not valid";
  } else {
    text = "Input OK";
  }
  document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>

Example 2

Result View Example

Automatic HTML Form Validation

HTML form validation can be performed automatically by the browser using the required attribute:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Validation</h2>
<p>From w3schools.com, Experiment by Teeratus_R</p>

<h4>Automatic HTML Form Validation</h4>
<form action="/action_page.php" method="post">
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <input type="submit" value="Submit">
</form>
<p>The required attribute prevents submission if the field is empty.</p>

</body>
</html>

Example 3

Result View Example

Data Validation

Data validation is the process of ensuring that user input is clean, correct, and useful.

Typical validation tasks:

Constraint Validation HTML Input Attributes

Attribute Description
required Specifies that an input field must be filled in
min / max Specifies min/max value of an input field
minlength / maxlength Specifies min/max length of text input
type Specifies the type of input (email, number, etc.)
pattern Specifies a regex pattern for input validation

HTML Constraint Validation

Constraint validation in HTML is based on:

Example: Input fields with type="email" will automatically be validated when the form is submitted. The :valid and :invalid CSS pseudo-classes allow you to style valid/invalid fields.

Document

Document in project

You can Download PDF file.

Reference