JavaScript , validate html form for both onkeyup and submit - javascript

I've see a lot of solution and questions similar to this but none of them helped me out
here is a simple html form with JavaScript validation
log error message on key up when the value of input fields are less than required length (less than 5)
log error message on submit when input fields are empty (first Name and last Name)
problem is when I click submit button form is submitted regardless of errors
I have tried preventDefault() and return false but none of them worked out
how can I improve the code to make them work correctly? for both key up and submit
let fname = document.getElementById('fname');
let lname = document.getElementById('lname');
form = document.querySelector('#myForm');
function checkFirstName() {
let valid = true;
if (fname.value.length < 5) {
console.log('first name must be greater than 5');
valid = false;
}
}
function checkLastName() {
let valid = true;
if (lname.value.length < 5) {
console.log('last name must be greater than 5');
valid = false;
}
}
form.addEventListener('input', function(e) {
switch (e.target.id) {
case 'fname':
checkFirstName();
break;
case 'lname':
checkLastName();
break;
}
});
form.addEventListener('submit', function(e) {
let isFormField = true;
if (fname.value === '') {
console.log('first name is required')
isFormField = false;
}
if (lname.value === '') {
console.log('last name is required')
isFormField = false;
}
if (!isFormField) {
e.preventDefault();
return
}
});
<form method="get" id="myForm">
<div>
<input type="text" class="form-control" id="fname" name="fname"></br>
<small class="small" id="small"></small>
</div>
<div>
<input type="text" class="form-control" id="lname" name="lname"></br>
<small class="small" id="small"></small>
</div>
<button type="submit" name="send">submit</button>
</form>

I've moved all the validation of firstname in the function checkFirstName and lastname in checkLastName. Just to be concise
You can make it separate, But you have to remember that form will only submit if checkFirstName and checkLastName returns true
let fname = document.getElementById('fname');
let lname = document.getElementById('lname');
form = document.querySelector('#myForm');
function checkFirstName() {
if (fname.value.length >= 5) return true;
if (fname.value === "") {
console.log('Last name is required')
return false
}
console.log('first name must be greater than 5');
return false;
}
function checkLastName() {
if (lname.value.length >= 5) return true;
if (lname.value === "") {
console.log('Last name is required')
return false
}
console.log('last name must be greater than 5');
return false;
}
form.addEventListener('input', function(e) {
switch (e.target.id) {
case 'fname':
checkFirstName();
break;
case 'lname':
checkLastName();
break;
}
});
form.addEventListener('submit', function(e) {
if (!checkFirstName() || !checkLastName()) {
e.preventDefault();
return
}
});
<form method="get" id="myForm">
<div>
<input type="text" class="form-control" id="fname" name="fname"></br>
<small class="small" id="small"></small>
</div>
<div>
<input type="text" class="form-control" id="lname" name="lname"></br>
<small class="small" id="small"></small>
</div>
<button type="submit" name="send">submit</button>
</form>

Related

Proper HTML Form Validation with JAVASCRIPT

here's simple html form validated with JavaScript , it show error message when the required fields are empty and when username is short(not satisfy the required length)..but form is sending data when submit button is clicked even if errors are displayed....how can i properly validate this form?
here's the code
let form = document.getElementById("signUp");
let uname = document.querySelector("#userName");
let uemail = document.querySelector("#userEmail");
const showError = (input, message) => {
// get the form-field element
const formField = input.parentElement;
// show the error message
const error = formField.querySelector('small');
error.textContent = message;
};
const showSuccess = (input) => {
// get the form-field element
const formField = input.parentElement;
// hide the error message
const error = formField.querySelector('small');
error.textContent = '';
}
const validateForm = () => {
if (uname.value.trim() == "") {
showError(uname, "name is empty");
return false;
} else {
showSuccess(uname);
}
if (uemail.value.trim() == "") {
showError(uemail, "email is empty");
return false;
} else {
showSuccess(uemail);
}
return true;
}
const checkUsername = () => {
const username = uname.value.trim();
if (username.length < 3) {
showError(uname, 'Username must be atleast 4 characters')
return false;
} else {
showSuccess(uname);
}
return true;
}
form.addEventListener('input', (event) => {
switch (event.target.id) {
case 'userName':
checkUsername();
break;
}
});
form.addEventListener("submit", function(e) {
if (!validateForm()) {
e.preventDefault();
}
});
<h2>JavaScript Validation</h2>
<form id="signUp" name="myForm">
<div>
Name: <input type="text" name="uname" id="userName">
<small id="showMessage" class="form-text text-muted"></small>
</div>
<div>
<br> Email: <input type="email" name="email" id="userEmail">
<small id="showMessage" class="form-text text-muted"></small>
</div>
<div>
<button type="submit">sign up</button>
</form>

Using the outcome of a function in another function [duplicate]

This question already has answers here:
How to prevent form from being submitted?
(11 answers)
Closed last year.
I have created 3 functions to cilentside validate a form for its name, email, and website, I would like to create a 4th function that checks if the outcome of the 3 first functions is true, we submit the form, if the outcome of any of them is false, the form doesn't get submitted. Below is my attempt for the JavaScript.
The purpose of this question is to learn how to use a 4th function to check the other 3 functions returns.
//validating name, email, website:
function nameValidation() {
var valid = true;
var name = document.getElementById("name1").value;
var validname = /^[a-zA-Z\s]*$/;
if (name == "") {
document.getElementById("errorMsg2").innerHTML = "* Name is required";
valid = false;
} else if (name.match(validname)) {
valid = true;
} else {
document.getElementById("errorMsg2").innerHTML = "* Only letters and white spaces allowed";
valid = false;
}
return valid;
}
function emailValidation() {
var valid = true;
var validEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var email = document.getElementById("email1").value;
if (email == "") {
document.getElementById("errorMsg3").innerHTML = "* Email is required";
valid = false;
} else if (email.match(validEmail)) {
valid = true;
} else {
document.getElementById("errorMsg3").innerHTML = "*Please enter a valid email.";
valid = false;
}
return valid;
}
function websiteValidation() {
var valid = true;
var validWebsite = /\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i;
var website = document.getElementById("website1").value;
if (website == "" || website.match(validWebsite)) {
valid = true;
} else {
document.getElementById("errorMsg4").innerHTML = "* Website is required";
valid = false;
}
return valid;
}
// function for form submission:
function formSubmit() {
if (nameValidation() == true && emailValidation() == true && websiteValidation() == true) {
return true;
} else {
return false;
}
}
document.getElementById("submit").addEventListener("click", () => {
console.log("Final result:", formSubmit());
});
<div>
<div id="errorMsg2"></div>
<input type="text" id="name1" />
</div>
<div>
<div id="errorMsg3"></div>
<input type="text" id="email1" />
</div>
<div>
<div id="errorMsg4"></div>
<input type="text" id="website1" />
</div>
<div>
<input type="submit" id="submit" />
</div>
Delete all of the JavaScript. This is the only HTML you need:
<input type="text" id="name1" pattern="[a-zA-Z\s]+" title="Letters and spaces only" required />
<input type="email" id="email1" required />
<input type="url" id="website1" required />
<input type="submit" id="submit" />
HTML5 Form validation has been around for a very long time at this point.

Not able to match patterns in HTML and JAVASCRIPT

Guys I coded this in html and js. It is just simple three inputs, NAME, EMAIL and PASSWORD. I validated this simple form in javascript but it is not working as expected. I wanted that if I give wrong input to any one of three inputs, it should alert me "Please enter valid credentials." and if I give right input to all of these, It should alert me "Congrats! your form submitted.".
The validation which I gave to NAME field is if length of name is less than 1, it should return false, else true. The validation which I gave to PASSWORD field is same as NAME field and you can see the validation which I gave to all field in my code below. When I give wrong input to only one field, it is still showing me "Congrats! your form submitted."
It is not working as expected!
function ValidateForm(username, email, password)
{
if ((validateusername(username) || validateemail(email) || validatepassword(password))==false)
{
alert("Please Enter Valid Credentials.")
return false
}
else if ((validateusername(username))==true && (validateemail(email))==true && (validatepassword(password))==true)
{
alert("Congrats! your form submitted.")
}
}
function validateemail(email)
{
var x = email.value;
var atposition = x.indexOf("#");
var dotposition = x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
{
return false;
}
else
{
return true
}
}
function validateusername(username)
{
if (username.length<1)
{
return false;
}
else
{
return true
}
}
function validatepassword(password)
{
if (password.length<1)
{
return false;
}
else
{
return true
}
}
<form name="myForm">
<input type="text" name="Name" placeholder="Enter Name">
<input type="text" name="EmailAddr" placeholder="Enter Email">
<input type="text" name="Password" placeholder="Enter Password">
<button type="submit" onclick="ValidateForm(document.myForm.Name, document.myForm.EmailAddr, document.myForm.Password)">Submit</button>
</form>
The problem is your if statement condition.
(validateusername(username) || validateemail(email) || validatepassword(password))==false
is the same as
!validateusername(username) && !validateemail(email) && !validatepassword(password)
so you're saying it should only be considered invalid if all 3 validations fail.
This function can be cleaned up and fixed at the same time:
function ValidateForm(username, email, password)
{
if (!validateusername(username) || !validateemail(email) || !validatepassword(password)) {
alert("Please Enter Valid Credentials.")
return false
}
else {
alert("Congrats! your form submitted.")
}
}
That's all you need. If any one of those fails, then the form fails. Otherwise (else) it's fine. You don't need to re-check again.
One improvement you can make is to take as few arguments as necessary without impeding clarity. This function is called "validate form" so I'd expect the form to be the argument, like this:
ValidateForm(document.myForm)
Which is easy to accommodate internally:
function ValidateForm(form)
{
if (!validateusername(form.username) || !validateemail(form.email) || !validatepassword(form.password)) {
alert("Please Enter Valid Credentials.")
return false
}
else {
alert("Congrats! your form submitted.")
}
}
Which requires renaming your form fields to be consistent:
<input type="text" name="name" placeholder="Enter Name">
<input type="text" name="email" placeholder="Enter Email">
<input type="text" name="password" placeholder="Enter Password">
Tip: Try and have one and only one name for your things. Calling it variously Name or name is really counter-productive.
I would avoid inlining events.
Take a look.
document.myForm.addEventListener("submit", validateForm);
function validateForm(event) {
event.preventDefault();
const {
Name: username,
EmailAddr: email,
Password: password,
} = document.myForm;
if (!validateUsername(username) ||
!validateEmail(email) ||
!validatePassword(password)) {
console.log("Please Enter Valid Credentials.")
return;
}
console.log("Congrats! your form submitted.");
}
function validateEmail(emailField) {
const x = emailField.value;
const atposition = x.indexOf("#");
const dotposition = x.lastIndexOf(".");
if (atposition < 1 ||
dotposition < atposition + 2 ||
dotposition + 2 >= x.length) {
return false;
}
return true
}
function validateUsername(username) {
if (username.length < 1) {
return false;
}
return true;
}
function validatePassword(password) {
if (password.length < 1) {
return false;
}
return true;
}
<form name="myForm">
<input type="text" name="Name" placeholder="Enter Name">
<input type="text" name="EmailAddr" placeholder="Enter Email">
<input type="text" name="Password" placeholder="Enter Password">
<button type="submit">Submit</button>
</form>

Input email control indexOf method

I have written this code but it doesn't work. I click the button check input:email and check the text.
function EpostaKontrol(eposta) {
if (eposta.indexof("#") != -1) {
var dizi = eposta.split("#");
if (!(alfaNummerikKonrol(dizi[0]))) {
if (domain.indexof(".") != -1) {
var domain = dizi[1].split(".");
if (dizi[0].length >= 3 && dizi[1].length >= 5 && domain[1].length >= 2)
alert("Email Format Wrong");
}
}
}
}
Please run the code snippet below:
function validateEmail(email) {
return /^([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x22([^\x0d\x22\x5c\x80-\xff]|\x5c[\x00-\x7f])*\x22))*\x40([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d)(\x2e([^\x00-\x20\x22\x28\x29\x2c\x2e\x3a-\x3c\x3e\x40\x5b-\x5d\x7f-\xff]+|\x5b([^\x0d\x5b-\x5d\x80-\xff]|\x5c[\x00-\x7f])*\x5d))*$/.test( email );
}
$(document).on( 'click', '#validate', function(){
var email = $('#email').val();
if (validateEmail(email))
console.log('This is a valid email!');
else
console.log('This is NOT a valid email!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="email"><input type="button" value="Validate if email" id="validate">
you can also achieve this by below code
mozilla Ref :
var email = document.getElementById("mail");
//email.setCustomValidity("I expect an e-mail, darling!");
email.addEventListener("input", function (event) {
checkEmail(email)
});
function checkEmail(email){
if (email.validity.patternMismatch) {
email.setCustomValidity("I expect an e-mail");
console.log("Invalid")
} else {
email.setCustomValidity("");
console.log("valid")
}
}
<h3>Show an e-mail field (allows only one email address):</h3>
<form action="/action_page.php">
E-mail: <input id='mail' type="email" name="emailaddress"pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
required>
<input type="submit" onclick="checkEmail(email)" >
</form>

Individual error messages for empty form fields using JavaScript

I need to validate my form using JavaScript because iPhone / Safari do not recognize the required attribute. I want individual error messages to appear below each empty input field.
My code works, but the individual error message does not disappear when the field is filled in. Also, I would like all messages to appear initially, for all empty fields (not one by one). I am very very new to JavaScript, sorry.
My HTML:
<form onsubmit="return validateForm()" method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
And my JavaScript:
<script>
function validateForm() {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").innerHTML = nameError;
return false;
}
else if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").innerHTML = emailError;
return false;
}
else if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").innerHTML = telephoneError;
return false;
}
else {return true;}
}
</script>
Thanks for your help.
Here is a solution that displays all relevant errors when the form is first submitted, and removes an error when the user modifies text in the relevant input element.
To get it to display all of the errors on first run, I used if statements instead of if else, and used a flag to determine whether the form should be submitted. To remove the warnings when the input is modified, I bound the onkeyup events of the inputs.
I ended up removing the required attributes on the inputs so that the demonstration will work in a modern browser that supports them.
Live Demo:
document.getElementById("english_registration_form").onsubmit = function () {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
var submit = true;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").innerHTML = nameError;
submit = false;
}
if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").innerHTML = emailError;
submit = false;
}
if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").innerHTML = telephoneError;
submit = false;
}
return submit;
}
function removeWarning() {
document.getElementById(this.id + "_error").innerHTML = "";
}
document.getElementById("name").onkeyup = removeWarning;
document.getElementById("email").onkeyup = removeWarning;
document.getElementById("telephone").onkeyup = removeWarning;
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" placeholder="Name"> <span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" placeholder="Email"> <span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" placeholder="Telephone"> <span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
JSFiddle Version: https://jsfiddle.net/xga2shec/
First of all, we change your function validateForm so it can handle multiple validations.
Then, we create a DOMContentLoaded event handler on the document, and we call the validateForm function, so we validate the field when the page is loaded.
And to finish, we create input event handlers on the inputs, so everytime someone change any data inside them, the form is validated again.
Take a look at the code commented, and see the working version in action!
function validateForm() {
var valid = true; // creates a boolean variable to return if the form's valid
if (!validateField(this, 'name')) // validates the name
valid = false;
if (!validateField(this, 'email')) // validates the email (look that we're not using else if)
valid = false;
if (!validateField(this, 'telephone')) // validates the telephone
valid = false;
return valid; // if all the fields are valid, this variable will be true
}
function validateField(context, fieldName) { // function to dynamically validates a field by its name
var field = document.forms['english_registration_form'][fieldName], // gets the field
msg = 'Please enter your ' + fieldName, // dynamic message
errorField = document.getElementById(fieldName + '_error'); // gets the error field
console.log(context);
// if the context is the form, it's because the Register Now button was clicked, if not, check the caller
if (context instanceof HTMLFormElement || context.id === fieldName)
errorField.innerHTML = (field.value === '') ? msg : '';
return field.value !== ''; // return if the field is fulfilled
}
document.addEventListener('DOMContentLoaded', function() { // when the DOM is ready
// add event handlers when changing the fields' value
document.getElementById('name').addEventListener('input', validateForm);
document.getElementById('email').addEventListener('input', validateForm);
document.getElementById('telephone').addEventListener('input', validateForm);
// add the event handler for the submit event
document.getElementById('english_registration_form').addEventListener('submit', validateForm);
});
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
you have to use style.display="none" to hide error
and style.display="block" to show error
<script>
function validateForm() {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").style.display="block";
document.getElementById("name_error").innerHTML = nameError;
return false;
}
else if (x != null || x != "") {
nameError = "Please enter your name";
document.getElementById("name_error").style.display="none";
return false;
}
if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").style.display="block";
document.getElementById("email_error").innerHTML = emailError;
return false;
}
else if (y != null || y != "") {
emailError = "Please enter your email";
document.getElementById("email_error").style.display="none";
return false;
}
if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").style.display="block";
document.getElementById("telephone_error").innerHTML = telephoneError;
return false;
}
else if (z != null || z != "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").style.display="none";
return false;
}
else {return true;}
}
</script>
function validateForm() {
var valid = true; // creates a boolean variable to return if the form's valid
if (!validateField(this, 'name')) // validates the name
valid = false;
if (!validateField(this, 'email')) // validates the email (look that we're not using else if)
valid = false;
if (!validateField(this, 'telephone')) // validates the telephone
valid = false;
return valid; // if all the fields are valid, this variable will be true
}
function validateField(context, fieldName) { // function to dynamically validates a field by its name
var field = document.forms['english_registration_form'][fieldName], // gets the field
msg = 'Please enter your ' + fieldName, // dynamic message
errorField = document.getElementById(fieldName + '_error'); // gets the error field
console.log(context);
// if the context is the form, it's because the Register Now button was clicked, if not, check the caller
if (context instanceof HTMLFormElement || context.id === fieldName)
errorField.innerHTML = (field.value === '') ? msg : '';
return field.value !== ''; // return if the field is fulfilled
}
document.addEventListener('DOMContentLoaded', function() { // when the DOM is ready
// add event handlers when changing the fields' value
document.getElementById('name').addEventListener('input', validateForm);
document.getElementById('email').addEventListener('input', validateForm);
document.getElementById('telephone').addEventListener('input', validateForm);
// add the event handler for the submit event
document.getElementById('english_registration_form').addEventListener('submit', validateForm);
});
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>

Categories

Resources