[[HTML5]] provides easy validation for forms to indicate to users when a field must be completed, simply add `validate` to the form field.
```HTML title="index.html"
<input id="fname" type="text" required>
```
However, this will not prevent the user from submitting incomplete data, it will only show the empty fields in red. To validate before entry, you need to adjust the JavaScript that runs the submit action.
```JavaScript title="JavaScript.html"
function submitForm(){
// create object to track fields and failure messages
var toValidate = {
fname: "First Name is Required",
lname: "Last Name is Required"
};
// loop through fields and validate
var idKeys = Object.keys(toValidate);
var allValid = true;
idKeys.forEach(function(elID){
var isValid = checkIfValid(elID, toValidate[elID]);
if(!isValid){
allValid = false;
}
});
// submitForm if all valid
if(allValid){
addRecord();
}
}
function checkIfValid(formField, message){
var isValid = document.getElementById(formField).checkValidity();
if(!isValid){
alert(message); // use a UI Framework for better messages (e.g. toast)
return False
} else {
return True;
} // END IF
}
function addRecord(){
var formResponses = {}
formResponses.firstName = document.getElementById("fname").value;
formResponses.lastName = document.getElementById("lname").value;
/// Code to write to output
}
```
You can add additional validation logic besides just whether it has content or not using `required pattern` and a regex expression. This will work well for email addresses, zip codes, phone numbers, and other data that have a standardized format.
```HTML title="index.html"
<input id="fname" type="text" required required pattern="^/d{5}
quot;>
```
Any additional validation would need to be done using JavaScript or on the server side.
> [!Warning]
> You must also prevent users from providing malicious inputs that will run on your server. This is called server-side validation.