Форма уже имеет встроенную функцию перенаправления с использованием атрибута action
, который также дает преимущество фактического размещения данных по желаемой ссылке, если это необходимо.
Более того form
имеет событие onsubmit
, которое выполняется перед отправкой формы и может быть отменено путем возврата false
.
Поскольку все упомянутые требования для вашего кода уже заданы поведением по умолчанию form
, меньше причин не использовать его.
Вот что вам нужно изменить:
- Вместо определения события щелчка вы определяете автономную функцию проверки (=
myValidator()
), который возвращает true
после выполнения всех критериев и false
до. В любом случае это лучшая хорошая практика, поскольку вы можете вызывать ее независимо от событий щелчка. - Установка
action
из form
на желаемый URL (= redirect.html
) - Пересылка
return
из myValidator()
до события onsubmit
на form
function myValidator(){
//REM: returns true once valid, false until.
var tReturn = true;
var firstName = document.getElementById('fname').value;
var lastName = document.getElementById('lname').value;
var yearBirth = document.getElementById('dob').value;
var phoneNum = document.getElementById('ph-no').value;
var emailID = document.getElementById('email').value;
var password = document.getElementById('password').value;
var rePassword = document.getElementById('re-password').value;
if (firstName.length === 0) {
alert('Enter the first name!');
tReturn = false
}else if (lastName.length === 0) {
alert('Enter the last name!');
tReturn = false
}else if (yearBirth.length === 0) {
alert('Enter date of birth!');
tReturn = false
}else if (phoneNum.length === 0) {
alert('Enter the phone number!');
tReturn = false
}else if (phoneNum.length > 10) {
alert('Check phone number!');
tReturn = false
}else if (emailID.length === 0) {
alert('Enter the email ID !');
tReturn = false
}else if (password.length === 0 && (rePassword.length === 0 || rePassword.length !== 0)) {
alert('Enter the password!');
tReturn = false
}else if (rePassword.length === 0) {
alert('Re-enter the password!');
tReturn = false
};
return tReturn
}
<!--REM: It is better practise to assign those events using javascript - I merely leave it here to point put the event/difference -->
<form class="input" action="redirect.html" onsubmit="return myValidator()">
<input class="input-field" id="fname" placeholder="First Name" type="text">
<input class="input-field" id="lname" placeholder="Last Name" type="text">
<input class="input-field" id="dob" placeholder="Date of Birth" type="date">
<input class="input-field" id="ph-no" placeholder="Phone Number" type="text">
<input class="input-field" id="email" placeholder="Email ID" type="email">
<input class="input-field" id="password" placeholder="Enter Password" type="password">
<input class="input-field" id="re-password" placeholder="Re-enter Password" type="password">
<button class="btn" id="sub-btn" type="submit">SIGN UP</button>
</form>
Также обратите внимание, что пустые входные данные в настоящее время можно предотвратить с помощью атрибута required , а также других приятных функций формы и соответствующего стиля с использованием псевдоклассов css.
<form class="input" action="redirect.html">
<input class="input-field" id="fname" placeholder="First Name" type="text" required>
<input class="input-field" id="lname" placeholder="Last Name" type="text" required>
<input class="input-field" id="dob" placeholder="Date of Birth" type="date" required>
<input class="input-field" id="ph-no" placeholder="Phone Number" type="text" required>
<input class="input-field" id="email" placeholder="Email ID" type="email" required>
<input class="input-field" id="password" placeholder="Enter Password" type="password" required>
<input class="input-field" id="re-password" placeholder="Re-enter Password" type="password" required>
<button class="btn" id="sub-btn" type="submit">SIGN UP</button>
</form>