The most viewed posts

Contact Me

About Me

Myanmar font and keyboard for Windows

Registry Reviver

IT Support & Endpoint Management

Digital Platforms & Web Solutions

How to clean up Windows Computer

Driver Booster

CCleaner

About Desktop Icons in Windows Computer

The most viewed items

Dell Inspiron 5559

SONY Playstation Portable

HP ProBook 430

Laptop RAM

External Hard Disk

Laptop

Desktop Hard Disk

Please login to start chat

ZilaStar ICT Nov 30 2025, 18:23:30
Category : JavaScript Tutorials

How to validate HTML Form with JavaScript

# HTML #
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="formvalidate.css">
<script src="formvalidate.js"></script>
</head>
<body>
<form action="formvalidate.html" method="post"
onsubmit="return formValidate();" id="myForm">
<div class="form-group">
<div class="form-control">
<label for="">Fullname</label>
<input type="text" name="fullname" id="fullname" onkeyup="chkFullname()">
</div>
<div class="form-control">
<label for="">Username</label>
<input type="text" name="username" id="username" onkeyup="chkUsername()">
</div>
<div class="form-control">
<input type="submit" value="Submit" class="btn-submit">
</div>
</div>
</form>
</body>

# CSS #

.form-group{
position: relative;
width: 320px;
border: 1px solid #ccc;
border-radius: 5px;
padding: 10px;
}
.form-control{
position: relative;
padding: 10px;
display: grid;
grid-auto-flow: column;
justify-items: center;
}
.btn-submit{
cursor: pointer;
}

# JavaScript #

function formValidate(){
var x = document.forms["myForm"]["fullname"].value;
var y = document.forms["myForm"]["username"].value;
if(x == ""){
alert("Required to fill in Fullname.");
return false;
}
if(y == ""){
alert("Required to fill in Username.");
return false;
}
if(x != "" && y != ""){
document.writeln("Successfully submited.");
document.writeln("<br/>");
document.writeln("Fullname = " + x +".");
document.writeln("<br/>");
document.writeln("Username = " + y +".");
return false;
}
}

//We don't allow special characters in Fullname
//We will only allow a to z, A to Z, 0 to 9 and space.

function chkFullname(){
var a = document.getElementById("fullname");
a.value = a.value.replace(/[^a-zA-Z0-9 ]/g, '');
}

//We will change all letters into small letters
function chkUsername(){
var b = document.getElementById("username");
b.value = b.value.toLowerCase();
b.value = b.value.replace(/[^a-zA-Z0-9]/g, '');//don't allow space
}


Comments:

No comment.

To Contact
🙏 About Me
📜Terms and Conditions