0% found this document useful (0 votes)
3 views2 pages

Form Validation Examples

The document provides an example of an HTML form with JavaScript validation for user inputs including first name, last name, age, and address. It ensures that first and last names are not empty, age is a positive number, and address is not empty before submission. Additionally, there is a mention of a slightly improved version with extra checks for validation.

Uploaded by

lencho03406
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Form Validation Examples

The document provides an example of an HTML form with JavaScript validation for user inputs including first name, last name, age, and address. It ensures that first and last names are not empty, age is a positive number, and address is not empty before submission. Additionally, there is a mention of a slightly improved version with extra checks for validation.

Uploaded by

lencho03406
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Complete Example (JavaScript + HTML)

<form onsubmit="return validateForm()">


First Name: <input type="text" id="fname"><br><br>
Last Name: <input type="text" id="lname"><br><br>
Age: <input type="number" id="age"><br><br>
Address: <input type="text" id="address"><br><br>

<button type="submit">Submit</button>
</form>

<script>
function validateForm() {
let fname = [Link]("fname").[Link]();
let lname = [Link]("lname").[Link]();
let age = [Link]("age").value;
let address = [Link]("address").[Link]();

// First Name validation


if (fname === "") {
alert("First name is required");
return false;
}

// Last Name validation


if (lname === "") {
alert("Last name is required");
return false;
}

// Age validation
if (age === "" || age <= 0) {
alert("Enter a valid age");
return false;
}

// Address validation
if (address === "") {
alert("Address is required");
return false;
}

return true; // form is valid


}
</script>

✅ What this validates:


 fname → cannot be empty
 lname → cannot be empty
 age → must be a positive number
 address → cannot be empty

👍 Slightly Better Version (Extra Checks)


If you want to make it more strict:

You might also like