// js加载时添加novalidate属性var forms =document.querySelectorAll('.validate');for (var i =0; i <forms.length; i++) { forms[i].setAttribute('novalidate',true);}
// Listen to all blur eventsdocument.addEventListener('blur',function (event) {// Only run if the field is in a form to be validatedif (!event.target.form.classList.contains('validate')) return;// Validate the fieldvar error =event.target.validity;console.log(error);},true);
// Validate the fieldvarhasError=function (field) {// Get the error};// Listen to all blur eventsdocument.addEventListner('blur',function (event) {// Only run if the field is in a form to be validatedif (!event.target.form.classList.contains('validate')) return;// Validate the fieldvar error =hasError(event.target);},true);
// Validate the fieldvarhasError=function (field) {// Don't validate submits, buttons, file and reset inputs, and disabled fieldsif (field.disabled ||field.type ==='file'||field.type ==='reset'||field.type ==='submit'||field.type ==='button') return;// Get validityvar validity =field.validity;};
如果没有错误,我们将返回null。否则,我们将检查每个有效状态属性,直到找到错误。
// Validate the fieldvarhasError=function (field) {// Don't validate submits, buttons, file and reset inputs, and disabled fieldsif (field.disabled ||field.type ==='file'||field.type ==='reset'||field.type ==='submit'||field.type ==='button') return;// Get validityvar validity =field.validity;// If valid, return nullif (validity.valid) return;// If field is required and emptyif (validity.valueMissing) return'Please fill out this field.';// If not the right typeif (validity.typeMismatch) return'Please use the correct input type.';// If too shortif (validity.tooShort) return'Please lengthen this text.';// If too longif (validity.tooLong) return'Please shorten this text.';// If number input isn't a numberif (validity.badInput) return'Please enter a number.';// If a number value doesn't match the step intervalif (validity.stepMismatch) return'Please select a valid value.';// If a number field is over the maxif (validity.rangeOverflow) return'Please select a smaller value.';// If a number field is below the minif (validity.rangeUnderflow) return'Please select a larger value.';// If pattern doesn't matchif (validity.patternMismatch) return'Please match the requested format.';// If all else fails, return a generic catchall errorreturn'The value you entered for this field is invalid.';};
// If not the right typeif (validity.typeMismatch) {// Emailif (field.type ==='email') return'Please enter an email address.';// URLif (field.type ==='url') return'Please enter a URL.';}
// If too shortif (validity.tooShort) return'Please lengthen this text to '+field.getAttribute('minLength') +' characters or more. You are currently using '+field.value.length+' characters.';// If too longif (validity.tooLong) return'Please short this text to no more than '+field.getAttribute('maxLength') +' characters. You are currently using '+field.value.length+' characters.';
如果数字字段超出或低于允许范围,我们可以在错误中包含最小或最大允许值。
// If a number field is over the maxif (validity.rangeOverflow) return'Please select a value that is no more than '+field.getAttribute('max') +'.';// If a number field is below the minif (validity.rangeUnderflow) return'Please select a value that is no less than '+field.getAttribute('min') +'.';
// If pattern doesn't matchif (validity.patternMismatch) {// If pattern info is included, return custom errorif (field.hasAttribute('title')) returnfield.getAttribute('title');// Otherwise, generic errorreturn'Please match the requested format.';}
这是我们的hasError()函数的完整代码:
// Validate the fieldvarhasError=function (field) {// Don't validate submits, buttons, file and reset inputs, and disabled fieldsif (field.disabled ||field.type ==='file'||field.type ==='reset'||field.type ==='submit'||field.type ==='button') return;// Get validityvar validity =field.validity;// If valid, return nullif (validity.valid) return;// If field is required and emptyif (validity.valueMissing) return'Please fill out this field.';// If not the right typeif (validity.typeMismatch) {// Emailif (field.type ==='email') return'Please enter an email address.';// URLif (field.type ==='url') return'Please enter a URL.'; }// If too shortif (validity.tooShort) return'Please lengthen this text to '+field.getAttribute('minLength') +' characters or more. You are currently using '+field.value.length+' characters.';// If too longif (validity.tooLong) return'Please shorten this text to no more than '+field.getAttribute('maxLength') +' characters. You are currently using '+field.value.length+' characters.';// If number input isn't a numberif (validity.badInput) return'Please enter a number.';// If a number value doesn't match the step intervalif (validity.stepMismatch) return'Please select a valid value.';// If a number field is over the maxif (validity.rangeOverflow) return'Please select a value that is no more than '+field.getAttribute('max') +'.';// If a number field is below the minif (validity.rangeUnderflow) return'Please select a value that is no less than '+field.getAttribute('min') +'.';// If pattern doesn't matchif (validity.patternMismatch) {// If pattern info is included, return custom errorif (field.hasAttribute('title')) returnfield.getAttribute('title');// Otherwise, generic errorreturn'Please match the requested format.'; }// If all else fails, return a generic catchall errorreturn'The value you entered for this field is invalid.';};
// Show the error messagevarshowError=function (field, error) {// Show the error message...};// Listen to all blur eventsdocument.addEventListener('blur',function (event) {// Only run if the field is in a form to be validatedif (!event.target.form.classList.contains('validate')) return;// Validate the fieldvar error =hasError(event.target);// If there's an error, show itif (error) {showError(event.target, error); }},true);
varshowError=function (field, error) {// Add error class to fieldfield.classList.add('error');// Get field id or namevar id =field.id ||field.name;if (!id) return;// Check if error message field already exists// If not, create onevar message =field.form.querySelector('.error-message#error-for-'+ id );if (!message) { message =document.createElement('div');message.className ='error-message';message.id ='error-for-'+ id;field.parentNode.insertBefore( message,field.nextSibling ); }// Update error messagemessage.innerHTML = error;// Show error messagemessage.style.display ='block';message.style.visibility ='visible';};
varshowError=function (field, error) {// Add error class to fieldfield.classList.add('error');// Get field id or namevar id =field.id ||field.name;if (!id) return;// Check if error message field already exists// If not, create onevar message =field.form.querySelector('.error-message#error-for-'+ id );if (!message) { message =document.createElement('div');message.className ='error-message';message.id ='error-for-'+ id;field.parentNode.insertBefore( message,field.nextSibling ); }// Add ARIA role to the fieldfield.setAttribute('aria-describedby','error-for-'+ id);// Update error messagemessage.innerHTML = error;// Show error messagemessage.style.display ='block';message.style.visibility ='visible';};
// Remove the error messagevarremoveError=function (field) {// Remove the error message...};// Listen to all blur eventsdocument.addEventListener('blur',function (event) {// Only run if the field is in a form to be validatedif (!event.target.form.classList.contains('validate')) return;// Validate the fieldvar error =event.target.validity;// If there's an error, show itif (error) {showError(event.target, error);return; }// Otherwise, remove any existing error messageremoveError(event.target);},true);
// Remove the error messagevarremoveError=function (field) {// Remove error class to fieldfield.classList.remove('error');// Remove ARIA role from the fieldfield.removeAttribute('aria-describedby');// Get field id or namevar id =field.id ||field.name;if (!id) return;// Check if an error message is in the DOMvar message =field.form.querySelector('.error-message#error-for-'+ id +'');if (!message) return;// If so, hide itmessage.innerHTML ='';message.style.display ='none';message.style.visibility ='hidden';};
// Show the error messagevarshowError=function (field, error) {// Add error class to fieldfield.classList.add('error');// If the field is a radio button and part of a group, error all and get the last item in the groupif (field.type ==='radio'&&field.name) {var group =document.getElementsByName(field.name);if (group.length>0) {for (var i =0; i <group.length; i++) {// Only check fields in current formif (group[i].form !==field.form) continue; group[i].classList.add('error'); } field = group[group.length-1]; } }...};
// Show the error messagevarshowError=function (field, error) {...// Check if error message field already exists// If not, create onevar message =field.form.querySelector('.error-message#error-for-'+ id );if (!message) { message =document.createElement('div');message.className ='error-message';message.id ='error-for-'+ id;// If the field is a radio button or checkbox, insert error after the labelvar label;if (field.type ==='radio'||field.type ==='checkbox') { label =field.form.querySelector('label[for="'+ id +'"]') ||field.parentNode;if (label) {label.parentNode.insertBefore( message,label.nextSibling ); } }// Otherwise, insert it after the fieldif (!label) {field.parentNode.insertBefore( message,field.nextSibling ); } }...};
// Remove the error messagevarremoveError=function (field) {// Remove error class to fieldfield.classList.remove('error');// If the field is a radio button and part of a group, remove error from all and get the last item in the groupif (field.type ==='radio'&&field.name) {var group =document.getElementsByName(field.name);if (group.length>0) {for (var i =0; i <group.length; i++) {// Only check fields in current formif (group[i].form !==field.form) continue; group[i].classList.remove('error'); } field = group[group.length-1]; } }...};
// Check all fields on submitdocument.addEventListener('submit',function (event) {// Validate all fields...},false);
如果表单具有.validate类,我们将获取每个字段,遍历每个字段,并检查错误。
// Check all fields on submitdocument.addEventListener('submit',function (event) {// Only run on forms flagged for validationif (!event.target.classList.contains('validate')) return;// Get all of the form elementsvar fields =event.target.elements;// Validate each field// Store the first field with an error to a variable so we can bring it into focus latervar error, hasErrors;for (var i =0; i <fields.length; i++) { error =hasError(fields[i]);if (error) {showError(fields[i], error);if (!hasErrors) { hasErrors = fields[i]; } } }// If there are errrors, don't submit form and focus on first element with errorif (hasErrors) {event.preventDefault();hasErrors.focus(); }// Otherwise, let the form submit normally// You could also bolt in an Ajax form submit process here},false);