In this article we will learn how to validate javascript form with most used common field like Name, Email, Password, Phone. These are the most common requirment when we are going to build Javascript forms Validation.
which need to be done at the client side befor going to server validations.
This is very Simple Javascript Form Validation you can just plug and play in your code itself
javascript form validation is most important steps we must need to do before sending the data to server end, so we restrict user on client side only beforw send it to server, it will increace the website performance and create a seemless feature between client and interface below are the most common validations we usually face while creating a form
So Lets learn form validation in html and javascript
- Name Validation: Checks if the name field is empty or contains any digits.
- Address Validation: Ensures the address field is not empty.
- Email Validation: Verifies if the email field is not empty and contains the ‘@’ symbol.
- Password Validation: Validates that the password field is not empty and has a minimum length of 6 characters.
- Field Empty Validation
If any validation criteria fails the we have a error handling approch to deal with it
- Error Handling:
- If any of the validation criteria fail, it displays an alert message using window.alert.
- Sets focus back to the respective field that failed validation, ensuring the user’s attention is drawn to the problematic field.
- Focus the error field : if any of the feild faced with an error the we need to focus the feilds step by step
So lets create a demo to form validation so you can use the code and impliment in your website
Javascript Form Validation Demo
HTML CODE
<div class="ss-form-Validation">
<div class="ss-forms">
<form>
<div class="ss-form-field">
<label>
Name
</label>
<input type="text" name="username" />
<p class="error-check error"></p>
</div>
<div class="ss-form-field">
<label>
Email
</label>
<input type="email" name="email" />
<p class="error-check error"></p>
</div>
<div class="ss-form-field">
<label>
Password
</label>
<input type="password" name="password" />
<p class="error-check error"></p>
</div>
<div class="ss-form-field">
<label>
Phone
</label>
<input type="text" name="phone" />
<p class="error-check error"></p>
</div>
<div class="ss-form-field">
<button disabled type="submit">Submit</button>
</div>
</form>
</div>
</div>
JAVASCRIPT CODE
<script>
let isPassValid, emailValid, nameValid , phoneValid;
const isValidUSPhoneNumber = (number) => {
const usPhoneNumberRegex = /^\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/;
return usPhoneNumberRegex.test(number);
}
const validateEmail = (email) => {
return String(email)
.toLowerCase()
.match(
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|.(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
)
}
const isValidPassword = (password) => {
const basicPasswordRegex = /^.{6,}$/
return basicPasswordRegex.test(password)
}
let fomrContainer = document.querySelector('.ss-forms')
let inputs = fomrContainer.querySelectorAll('input')
inputs.forEach((ele) => {
ele.addEventListener('keyup', function (event) {
if (event.target.name == 'email') {
let isEmailTrue = validateEmail(event.target.value)
if (isEmailTrue == null) {
emailValid = false;
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check').innerHTML =
'Please Enter Correct Email'
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check')
.classList.add('error')
} else {
emailValid = true;
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check')
.classList.remove('error')
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check').innerHTML = 'Email Validated'
}
}
if (event.target.name == 'username') {
if (event.target?.value?.length > 2) {
nameValid = true;
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check')
.classList.remove('error')
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check').innerHTML = 'Name Validate'
} else {
nameValid = false;
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check').innerHTML =
'Please enter name more then 3 letters'
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check')
.classList.add('error')
}
}
if (event.target.name == 'password') {
let validPassword = isValidPassword(event.target.value)
if (validPassword) {
isPassValid = true;
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check')
.classList.remove('error')
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check').innerHTML = 'Password Validated'
} else {
isPassValid = false;
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check').innerHTML =
'^ and $: Assert position at the start and end of the string </br> {6,}: Matches any character (.) at least 6 times ({6,}).'
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check')
.classList.add('error')
}
}
if (event.target.name == 'phone') {
let validateNum = isValidUSPhoneNumber(event.target.value)
if (validateNum) {
phoneValid = true;
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check')
.classList.remove('error')
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check').innerHTML = 'Phone Number Validated'
} else {
phoneValid = false;
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check').innerHTML =
'Enter Valid Phone Number'
ele.parentElement
.closest('.ss-form-field')
.querySelector('.error-check')
.classList.add('error')
}
}
if(isPassValid && emailValid && nameValid && phoneValid) {
document.querySelector("form").querySelector("button").disabled = false;
}
})
})
</script>