How to improve my validation in JavaScript?
Namely I am wondering whether some parts of code can be shortened, improved, or removed althogether.
I don't want to change the ES5 syntax because so far I am not familiar with Es6 syntax.
I also want to avoid using jQuery.
This is my validation code: https://codepen.io/RobotHabanera/pen/NWbKJLe
var form = document.querySelector('form');
var errormessage = document.querySelector('.error-message');
form.addEventListener('submit', function(e) {
e.preventDefault();
// musimy zalożyć czy formularz jest poprawnie wypełniony czy nie
var errors = [];
errormessage.innerHTML = '';
var clearAllParagraphsAtTheStart = document.querySelectorAll('.form-group p');
clearAllParagraphsAtTheStart.forEach(function(item) {
item.innerHTML = '';
});
// sprawdzić czy walidacja bedzie działać
for (var i = 0; i < form.elements.length; i++) {
var field = form.elements[i];
switch (field.name) {
case 'email':
// najpierw negujemy funkcje hasMonkeyInFiled i jesli negacja przebiegnie prawidłowo to wykona się prawa strona komunikatu && bo
// jesli negacja nie przebiegnie prawidłowo to linijka z prawej sterony sie nie wykona.
!hasMonkeyInFiled(field) && errors.push({
email: 'Email musi posiadać znak @'
});
break;
case 'name':
!hasMoreThanTwoChars(field) && errors.push({
name: 'Twoje imię jest za krótkie'
});
break;
case 'surname':
!hasMoreThanSixChars(field) && errors.push({
surname: 'Twoje nazwisko jest za krótkie'
});
break;
case 'pass1':
!hasCorrectPassword(field, form.elements[i + 1]) && errors.push({
pass1: 'Hasła nie są takie same lub puste'
});
break;
case 'pass2':
!hasCorrectPassword(field, form.elements[i - 1]) && errors.push({
pass2: 'Hasła nie są takie same lub puste'
});
break;
case 'agree':
!isChecked(field) && errors.push({
agree: 'Musisz zaakceptować warunki'
});
break;
}
}
if (errors.length) {
e.preventDefault();
errors = errors.filter(function(v, i, a) {
return a.indexOf(v) === i;
});
errors.forEach(function(item, index) {
// wklej wartość klucza z tablicy errors gdzie nazwa klucza jest równa wartości danego data-validation bierzącego inputa z pętli
var currentKey = Object.keys(errors[index]);
var currentValue = Object.values(errors[index]);
var inputs = document.querySelectorAll('.form-group input');
inputs.forEach(function(item, index) {
if (item.dataset.validation == currentKey) {
var elementP = document.createElement('p');
elementP.innerHTML = currentValue;
item.after(elementP);
}
});
/* errormessage.append(elementP); */
});
}
});
function hasCorrectPassword(field1, field2) {
if (hasMatch(field1, field2) && hasNumberChar(field1) && hasNumberChar(field1)) {
return true;
}
return false;
}
// paramertr 'field' to jest input element
function hasMonkeyInFiled(field) {
return field.value.indexOf('@') > -1;
}
// input ma wiecej niz 6 znakow
function hasMoreThanSixChars(field) {
return field.value.length > 6;
}
// input ma wiecej niz 2 znaki
function hasMoreThanTwoChars(field) {
return field.value.length > 2;
}
// checkbox musi byc zaznaczony
function isChecked(field) {
return field.checked;
}
// pierwsze i drugie hasło są identyczne ale nie puste
function hasMatch(field1, field2) {
// jak sprawdzic czy nie sa puste
if (field1.value.length && field1.value.length) {
return field1.value == field2.value;
}
return false;
}
// Warunek dla chętnych. Dodatkowe. Hasło ma mieć co najmniej 6 znaków (w tym co najmniej jedną liczbę i jedną literę)
function hasNumberChar(field) {
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var hasNumber = false;
numbers.forEach(function(number) {
if (field.value.indexOf(number) > -1) {
hasNumber = true;
}
});
return hasNumber;
}
function hasLetterChar(field) {
var chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
var hasChar = false;
chars.forEach(function(char) {
if (field.value.toLowerCase().indexOf(chars) > -1) {
hasChar = true;
}
});
return hasChar;
}
// input ma wiecej niz 5 znakow
function hasMoreThanFiveChars(field) {
return field.value.length > 5;
}
function isPangram(string) {
string.replace(/ /g, '');
for (var i = 0; i < string.trim().length; i++) {
var array = [];
var chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
chars.forEach(function(char) {
if (char == string.substr(string[i], 1)) {} else {
array.push(string[i])
}
});
}
if (array.length) {}
// bierze pierwszą litere z tablicy i jedzie tą literą po wszystkich znakach tekstu
string.replace(/ /g, '');
chars.forEach(function(char) {
for (var i = 0; i < string.length; i++) {
var chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
if (char == string[i]) {
console.log('jest');
} else {
console.log('nie ma');
}
}
});
};
function isPangram(string) {
string.replace(/ /g, '');
var array = [];
var chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
chars.forEach(function(char) {
for (var i = 0; i < string.length; i++) {
// każda litera alfabetu ma przejechać po tekście
if (char == string[i]) {
array.push(string[i]);
} else {}
}
if (array.length > 0) {
console.log('jest')
}
});
};
You should look at using regex for at least your tests for numbers or letters:
// match a letter, number or underscore
string.match(/\w/);
// Match a-z and A-Z (the i at the end makes case insensitive) - this could replace hasLetterChar()
string.match(/[a-z]/i);
// match a number - that could replace hasNumberChar()
string.match(/\d/);
Of course you can combine these to make a total test in one go. Actually, that would be better, together with /^ $/, that will make the test only pass if it matches from start to end of the string. That way you will not get any unexpected input.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.