I'm new to JavaScript and am struggling to wrap my head around this one.
I have an HTML form with some required input fields which have onblur
validation. I want to fix my code so that when the form is submitted without a user having filled in those required fields, the error messages show up instead of the form actually submitting like it is currently.
I realise similar questions have been asked however I was unable to implement suggested methods and have been researching this for days. I also require a pure JavaScript method, so how can I ensure all of the empty required fields throw their error messages when the submit button is clicked?
This is my first time posting a question - I hope I've covered everything, please let me know if I need to include anything else! Thanks in advance.
<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")
}
You have to call your javascript validation function in you code.
<form name="" method="" onsumbmit="return myfunction()">
<!-- Your code -->
</form>
And in your javascript code, if everything is right then return true else return false and display appropriate message.
function myfunction(){
<!-- here your validation conditions -->>
if(everything==ok)
return true;
else
return false;
}
摆脱表单上的novalidate
属性。
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.