저는 JavaScript를 처음 사용하고 있으며 내 머리를 감싸는 데 어려움을 겪고 있습니다.JavaScript 유효성 검사 문제 - 불완전한 경우에도 HTML 양식이 제출됩니다.
일부 입력 입력란에 HTML 양식이 있으며 onblur
유효성 확인이 있습니다. 양식을 사용자가 해당 필드에 채우지 않고 제출할 때 오류 메시지가 실제 양식처럼 실제로 제출하는 대신 표시되도록 내 코드를 수정하고 싶습니다.
나는 비슷한 질문을했지만 나는 제안 된 방법을 구현할 수 없었으며 이것을 수 일간 연구 해왔다. 또한 순수 JavaScript 메서드가 필요하므로 제출 단추를 클릭 할 때 빈 필드가 모두 오류 메시지를 던지지 않도록하려면 어떻게해야합니까?
질문을 게시 한 것은 이번이 처음입니다. 모든 것을 다 커버했으면 좋겠어요. 다른 것을 포함해야한다면 알려주세요! 미리 감사드립니다.
<form id="contact-form" method="POST" action="contact.html" novalidate>
<p>Text</p>
<div class="form-group">
<select name="flights" size="1">
<option value="" disabled selected hidden>Select Flight</option>
<option value="helicopter">Helicopter</option>
<option value="aerobatic">Aerobatic</option>
<option value="tramping">Tramping</option>
<option value="amphibian">Amphibian</option>
<option value="glider">Glider</option>
<option value="private-charter">Private Charter</option>
</select>
</div>
<div class="form-group">
<label>Flight Duration</label>
<br>
<select name="flight-duration" size="1">
<option value="" disabled selected hidden>Select Duration</option>
<option value="helicopter">1 Hour</option>
<option value="tramping">2 Hours</option>
<option value="amphibian">3 Hours</option>
<option value="glider">Custom</option>
</select>
</div>
<div class="form-group">
<label>Booking Date</label>
<br>
<select id="dayDropDown">
</select>
<select id="monthDropDown">
</select>
<select id="yearDropDown">
</select>
</div>
<div class="form-group">
<label for="firstname"></label>
<input id="firstname" type="text" onblur="blur()" name="firstname" placeholder="First Name" required autofocus minlength="2">
<span id="firstname-error"></span>
</div>
<div class="form-group">
<label for="lastname"></label>
<input id="lastname" type="text" name="lastname" placeholder="Last Name" required minlength="2">
<span id="lastname-error"></span>
</div>
<div class="form-group">
<label for="phone"></label>
<input id="phone" type="tel" name="phone" placeholder="Phone Number" required minlength="8">
<span id="phone-error"></span>
</div>
<div class="form-group">
<label for="email"></label>
<input id="email" type="email" name="email" placeholder="Enter valid email address" required>
<span id="email-error"></span>
</div>
<div class="form-group">
<label for="country"></label>
<input id="country" type="text" name="country" placeholder="Country" required minlength="2">
<span id="country-error"></span>
</div>
<div class="form-group">
<textarea placeholder="What can we do for you?"></textarea>
</div>
<div class="form-group">
<button class="submit" type="submit">Submit</button>
</div>
</form>
/****************
*FORM-VALIDATION*
****************/
//convert user input to upper case
function addFormValidation(theForm) {
if (theForm === null || theForm.tagName.toUpperCase() !== 'FORM') {
throw new Error("expected first parameter to addFormValidation to be a FORM.");
}
theForm.noValidate = true;
theForm.addEventListener('submit', function (evt) {
var isError = false;
var elements = this.elements;
for (var i = 0; i < elements.length; i += 1) {
if (!isFieldValid(elements[i])) {
isError = true;
}
}
if (isError) {
evt.preventDefault();
}
});
function isFieldValid(field) {
var errorMessage = "";
function isFieldValid(field) {
if (!needsToBeValidated(field)) {
return true;
}
if (field.id.length === 0 || field.name.length === 0) {
console.error("error: ", field);
throw new Error("found a field that is missing an id and/or name attribute." +
" name should be there. id is required for determining the field's error message element.");
}
field.classList.remove('invalid');
var errorSpan = document.querySelector('#' + field.id + '-error');
if (errorSpan === null) {
console.error("error: ", field);
throw new Error("could not find the '#" + field.id + "-error' element. It's needed for error messages if #" + field.id + " is ever invalid.");
}
errorSpan.classList.remove('danger');
errorSpan.innerHTML = "";
if (field.minLength > 0 && field.value.length < field.minLength) {
errorMessage = "Must be " + field.minLength + " or more characters long.";
}
if (field.maxLength > -1 && field.value.length > field.maxLength) {
errorMessage = "Must be " + field.maxLength + " characters or less.";
}
if (field.type === "email" && !isEmail(field.value)) {
errorMessage = "This should be a valid email address.";
}
if (field.required && field.value.trim() === "") {
errorMessage = "This field is required.";
}
if (errorMessage !== "") {
field.classList.add('invalid');
errorSpan.classList.add('danger');
errorSpan.innerHTML = errorMessage;
return false;
}
return true;
}
//fields that do not require validation
// function needsToBeValidated(field) {
// return ['submit', 'reset', 'button', 'hidden', 'radio', 'fieldset', 'select'].indexOf(field.type) === -1;
// }
function needsToBeValidated(field) {
return ['submit', 'reset', 'button', 'hidden', 'fieldset'].indexOf(field.type) === -1;
}
//email regx pattern to ensure email input is a valid email
function isEmail(input) {
return input.match(/^([a-z0-9_.\-+]+)@([\da-z.\-]+)\.([a-z\.]{2,})$/);
}
//add onblur validation to provide error/success info for user
var elements = theForm.elements;
for (var j = 0; j < elements.length; j++) {
elements[j].addEventListener('blur', function() {
isFieldValid(event.target);
})
};
}
//wait for content to load before loading form
document.addEventListener('DOMContentLoaded', function() {
addFormValidation(document.querySelector('#contact-form'))
});
/***********************************************
* Implemented this date selector script for use on contact form:
* Drop Down Date select script- by JavaScriptKit.com
* This notice MUST stay intact for use
* Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and more
***********************************************/
var monthtext = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
function populatedropdown(dayfield, monthfield, yearfield) {
var today = new Date()
var dayfield = document.getElementById(dayfield)
var monthfield = document.getElementById(monthfield)
var yearfield = document.getElementById(yearfield)
for (var i = 0; i < 31; i++)
dayfield.options[i] = new Option(i, i + 1)
dayfield.options[today.getDate()] = new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m = 0; m < 12; m++)
monthfield.options[m] = new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()] = new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear = today.getFullYear()
for (var y = 0; y < 20; y++) {
yearfield.options[y] = new Option(thisyear, thisyear)
thisyear += 1
}
yearfield.options[0] = new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload = function() {
populatedropdown("dayDropDown", "monthDropDown", "yearDropDown")
}
'제안 된 방법을 구현할 수 없습니다. '- 왜? 또한,'console'에 오류가 있습니까? –
@MoshFeu 콘솔에 오류가 없습니다. 그러나 '가능한 존재하지 않는 속성'이라고하는 Closure Compiler를 사용할 때 경고 메시지가 나타납니다. 참조하는 코드는 if (field.minLength> 0 && field. value.length