2022 Vanilla JS-Lösung
Pure JavaScript hat alle Funktionen, die Sie dafür brauchen. Ich weiß, die Frage bezog sich auf jQuery, aber auch die Antworten mit jQuery verwenden diese Funktionen, die sind checkValidity()
y reportValidity()
.
Test des gesamten Formulars
let form = document.getElementById('formId');
// Eventlistener can be another event and on another DOM object this is just an example
form.addEventListener('submit', function (event) {
// Only needed if event is submit, otherwise this line can be skipped
event.preventDefault();
// This is the important part, test if form is valid
if (form.checkValidity() === false){
// This is the magic function that displays the validation errors to the user
form.reportValidity();
return;
}
// Code if all fields are valid; continue form submit or make Ajax call.
})
Testspezifisches Feld
checkValidity()
y reportValidity()
kann nicht nur für das Formular, sondern auch für bestimmte Felder verwendet werden. Es ist nicht nötig, ein Formular oder eine Dummy-Schaltfläche zum Absenden zu erstellen, wenn sie nicht benötigt werden.
// Get field of interest
let inputElement = document.querySelector("[name='" + inputName + "']");
// Check if the element is valid
if (inputElement.checkValidity() === false){
// If not, show the errors to the user
inputElement.reportValidity();
return;
}
// Nothing? Great, continue to the Ajax call or whatever
Dies muss natürlich in einer Funktion geschehen, die von einem Ereignis-Listener aufgerufen wird, damit es Sinn macht.