Валидация формы на JavaScript

Вариант первый, в котором скрипт находится непосредственно под самой формой

Есть форма (пример взят с проекта, который работает на ProcessWire).

Пример кода

<form class="uk-modal-rent-form" onsubmit="return validateForm();" action="" method="post">

			<div class="uk-form-controls uk-flex">
				<label class="uk-modal-rent-label" id="name_modal-rent-label" for="name_modal-rent"><?php echo $pages->get('template=modal_rent')->label; ?></label>
				<input class="uk-modal-rent-input" type="text" id="name_modal-rent" name="name" placeholder="<?php echo $pages->get('template=modal_rent')->text; ?>">
			</div>

			<div class="uk-form-controls uk-flex uk-inline" style="z-index: 3;">
				<label class="uk-modal-rent-label" for="communication_modal-rent"><?php echo $pages->get('template=modal_rent')->label_02; ?></label>
				<button class="uk-modal-rent-button" type="button">
					<input class="uk-modal-rent-input-select communication" type="text" id="communication_modal-rent" name="communication" placeholder="<?php echo $pages->get('template=modal_rent')->text_02; ?>" value="a call" readonly="readonly">
					<img class="uk-modal-rent-logo-droopdown" src="<?php echo $config->urls->assets; ?>images/droopdown.svg" alt="" uk-img>
				</button>
				<div class="uk-modal-rent-selectblock selectblock-communication" uk-dropdown="mode: click">
					<p class="uk-modal-rent-selectblock-item communication">a call</p>
					<p class="uk-modal-rent-selectblock-item communication">text message</p>
				</div>
			</div>

			<div class="uk-form-controls uk-flex">
				<label class="uk-modal-rent-label" id="phone_modal-rent-label" for="phone_modal-rent"><?php echo $pages->get('template=modal_rent')->label_03; ?></label>
				<input class="uk-modal-rent-input-phone" type="text" id="phone_modal-rent" name="phone" placeholder="+1 (999) 999-99-99">
				<img class="uk-modal-rent-input-phone-img" src="<?php echo $config->urls->assets; ?>images/phone-america.svg" alt="" uk-img>
			</div>

			<div class="uk-form-controls uk-flex uk-hidden">
				<input class="uk-modal-rent-input" type="text" id="type_modal-rent" name="type">
			</div>

			<div class="uk-form-controls uk-flex uk-hidden">
				<input class="uk-modal-rent-input" type="text" id="need_e-bikes_modal-rent" name="need_e-bikes">
			</div>

			<div class="uk-form-controls uk-flex uk-hidden">
				<input class="uk-modal-rent-input" type="text" id="bike_model_modal-rent" name="bike_model">
			</div>

			<div class="uk-form-controls uk-flex">
				<label class="uk-modal-rent-label" for="promocode_modal-rent"><?php echo $pages->get('template=modal_rent')->label_04; ?></label>
				<input class="uk-modal-rent-input" type="text" id="promocode_modal-rent" name="promocode" placeholder="<?php echo $pages->get('template=modal_rent')->text_03; ?>">
			</div>

			<div class="uk-form-controls uk-flex uk-inline">
				<label class="uk-modal-rent-label" for="lang_modal-rent"><?php echo $pages->get('template=modal_rent')->label_05; ?></label>
				<button class="uk-modal-rent-button" type="button">
					<input class="uk-modal-rent-input-select lang" type="text" id="lang_modal-rent" name="lang" placeholder="" value="English" readonly="readonly">
					<img class="uk-modal-rent-logo-droopdown" src="<?php echo $config->urls->assets; ?>images/droopdown.svg" alt="" uk-img>
				</button>
				<div class="uk-modal-rent-selectblock selectblock-lang" uk-dropdown="mode: click">
					<p class="uk-modal-rent-selectblock-item lang">English</p>
					<p class="uk-modal-rent-selectblock-item lang">Espanol</p>
				</div>
			</div>

			<div class="uk-modal-rent-submit uk-flex uk-flex-center">
				<button class="uk-modal-rent-submit-btn" type="submit"><?php echo $pages->get('template=modal_rent')->button_one; ?></button>
			</div>

			<div class="uk-modal-rent-footer">
				<p class="uk-modal-rent-footer-txt"><?php echo $pages->get('template=modal_rent')->info_text; ?></p>
			</div>

		</form>

Главная строка, которая отвечает за отправку - onsubmit="return validateForm();".

И сам скрипт, который проверят наши поля и в зависимости от проверки выдает ошибку, которую можно оформить по разному.

script

<script>
	function validateForm() {
		console.log("validform");

		// Validate Name
		var name = document.getElementById("name_modal-rent").value;
		console.log(name.length);
		if (name.length < 3) {
			console.log("notsubmit");
			document.getElementById("name_modal-rent-label").classList.add("errorinput");
			return false;
		} else {
			console.log("submit");
			document.getElementById("name_modal-rent-label").classList.remove("errorinput");
		}

		// Validate Phone
		var phone = document.getElementById("phone_modal-rent").value;
		console.log(phone.length);
		if (phone.length < 18) {
			console.log("notsubmit");
			document.getElementById("phone_modal-rent-label").classList.add("errorinput");
			return false;
		} else {
			console.log("submit");
			document.getElementById("phone_modal-rent-label").classList.remove("errorinput");
		}

		return true;
	}
</script>

 

Вариант второй, в которым скрипт находится в отдельном файле main.js

Есть форма (пример взят с проекта, который работает на ProcessWire). В этом случае, нам  onsubmit="return validateForm();".

Форма

<form class="uk-modal-rent-form" action="" method="post">

			<div class="uk-form-controls uk-flex">
				<label class="uk-modal-rent-label" id="name_modal-rent-label" for="name_modal-rent"><?php echo $pages->get('template=modal_rent')->label; ?></label>
				<input class="uk-modal-rent-input" type="text" id="name_modal-rent" name="name" placeholder="<?php echo $pages->get('template=modal_rent')->text; ?>">
			</div>

			<div class="uk-form-controls uk-flex uk-inline" style="z-index: 3;">
				<label class="uk-modal-rent-label" for="communication_modal-rent"><?php echo $pages->get('template=modal_rent')->label_02; ?></label>
				<button class="uk-modal-rent-button" type="button">
					<input class="uk-modal-rent-input-select communication" type="text" id="communication_modal-rent" name="communication" placeholder="<?php echo $pages->get('template=modal_rent')->text_02; ?>" value="a call" readonly="readonly">
					<img class="uk-modal-rent-logo-droopdown" src="<?php echo $config->urls->assets; ?>images/droopdown.svg" alt="" uk-img>
				</button>
				<div class="uk-modal-rent-selectblock selectblock-communication" uk-dropdown="mode: click">
					<p class="uk-modal-rent-selectblock-item communication">a call</p>
					<p class="uk-modal-rent-selectblock-item communication">text message</p>
				</div>
			</div>

			<div class="uk-form-controls uk-flex">
				<label class="uk-modal-rent-label" id="phone_modal-rent-label" for="phone_modal-rent"><?php echo $pages->get('template=modal_rent')->label_03; ?></label>
				<input class="uk-modal-rent-input-phone" type="text" id="phone_modal-rent" name="phone" placeholder="+1 (999) 999-99-99">
				<img class="uk-modal-rent-input-phone-img" src="<?php echo $config->urls->assets; ?>images/phone-america.svg" alt="" uk-img>
			</div>

			<div class="uk-form-controls uk-flex uk-hidden">
				<input class="uk-modal-rent-input" type="text" id="type_modal-rent" name="type">
			</div>

			<div class="uk-form-controls uk-flex uk-hidden">
				<input class="uk-modal-rent-input" type="text" id="need_e-bikes_modal-rent" name="need_e-bikes">
			</div>

			<div class="uk-form-controls uk-flex uk-hidden">
				<input class="uk-modal-rent-input" type="text" id="bike_model_modal-rent" name="bike_model">
			</div>

			<div class="uk-form-controls uk-flex">
				<label class="uk-modal-rent-label" for="promocode_modal-rent"><?php echo $pages->get('template=modal_rent')->label_04; ?></label>
				<input class="uk-modal-rent-input" type="text" id="promocode_modal-rent" name="promocode" placeholder="<?php echo $pages->get('template=modal_rent')->text_03; ?>">
			</div>

			<div class="uk-form-controls uk-flex uk-inline">
				<label class="uk-modal-rent-label" for="lang_modal-rent"><?php echo $pages->get('template=modal_rent')->label_05; ?></label>
				<button class="uk-modal-rent-button" type="button">
					<input class="uk-modal-rent-input-select lang" type="text" id="lang_modal-rent" name="lang" placeholder="" value="English" readonly="readonly">
					<img class="uk-modal-rent-logo-droopdown" src="<?php echo $config->urls->assets; ?>images/droopdown.svg" alt="" uk-img>
				</button>
				<div class="uk-modal-rent-selectblock selectblock-lang" uk-dropdown="mode: click">
					<p class="uk-modal-rent-selectblock-item lang">English</p>
					<p class="uk-modal-rent-selectblock-item lang">Espanol</p>
				</div>
			</div>

			<div class="uk-modal-rent-submit uk-flex uk-flex-center">
				<button class="uk-modal-rent-submit-btn" type="submit"><?php echo $pages->get('template=modal_rent')->button_one; ?></button>
			</div>

			<div class="uk-modal-rent-footer">
				<p class="uk-modal-rent-footer-txt"><?php echo $pages->get('template=modal_rent')->info_text; ?></p>
			</div>

		</form>

 И скрипт, main.js.

main.js

//Validation Form
var form = document.querySelector('.uk-modal-rent-form');
form.addEventListener('submit', function (event) {
	event.preventDefault();
	console.log('clicked on validate');
	validateForm();
});

function validateForm() {
	console.log("validform");

	// Validate Name
	var name = document.getElementById("name_modal-rent").value;
	console.log(name.length);
	if (name.length < 3) {
		console.log("notsubmit");
		document.getElementById("name_modal-rent-label").classList.add("errorinput");
		return false;
	} else {
		console.log("submit");
		document.getElementById("name_modal-rent-label").classList.remove("errorinput");
	}

	// Validate Phone
	var phone = document.getElementById("phone_modal-rent").value;
	console.log(phone.length);
	if (phone.length < 18) {
		console.log("notsubmit");
		document.getElementById("phone_modal-rent-label").classList.add("errorinput");
		return false;
	} else {
		console.log("submit");
		document.getElementById("phone_modal-rent-label").classList.remove("errorinput");
	}

	console.log("отправляем форму");
	document.querySelector('.uk-modal-rent-form').submit();
	return true;
}

 

Так же с моим портфолио можно ознакомиться на любой из представленной социальной сети, на своих страницах я публикую посты о своих работах, заданиях и целях.

Для связи со мной можно воспользоваться любой социальной сетью,
или написать на почту:

С моим резюме можно ознакомиться по ссылке:

© 2020-2024 Портфолио Юдина Александра г.Пенза. Все права защищены