Isn’t it a case of checking each field when the user moves away from it (onBlur(), perhaps?) and running the validation at that point, and either throwing an error message or just showing an appropriate message / icon to indicate validity?
I wouldn’t like to, I’m mainly on here to learn stuff. I could probably cobble something together, but I’m sure there are far more knowledgeable people on here that can point to a decent tutorial or a much simpler method than I might think up. There’s an article on Sitepoint but it’s dated 2016 and talks about using JQuery below version 2, which seems quite old to me. Maybe someone knows of an updated version. There was quite a discussion about form validation on here recently, but I can’t find it now.
It’s usually best for functions that handle events to be suitably named.
In this case, it’s a function that accepts an event object, so that it can easily get the form from that object.
function formChangeHandler(evt) {
var field = evt.target;
var form = field.form;
// add code below here, that runs every time a form field is changed.
...
}
ok now I have done this
for example here I amm doing it just for name attribute to make this simple to understand
function formChangeHandler(event) {
var field = event.target;
var form = field.form;
var name = $('#name').val();
$(".error").remove();
// $(".error").css("color", "red");
if (name.length < 1) {
$('#name').after('<span class="error">This field is required</span>');
}
else{
//some code
}
</script>
is this correct ? and how will my submit event will appen then? I tried it in other ways but that didn’t work.
Sorry for the spelling mistake, I have updated it now
Also, attempting to send the form each and every time that the form changes, is very bad behavior.
You should not have that send function anywhere near the formChangeHandler function.
When the form fields are being validated on each and every change, that is no place at all for the send function.
The send function belongs in a completely different place, on a form submit event function instead.
You can put it anywhere that it can access the form. It’s normally recommended that even handlers are among the last functions on the page, which allows them to access and use everything else above them.
hey thanks for your suggestions , I have found another easy way to do this I did it just by adding this line
$("#contact_form").on('change', 'input', function() {
//my validation code here
}
and then cling send functon on clicking submit
and thats solved my real time validation issue .
but still the form is not submiting twice after first submit untill I refresh the page
How can I fix it ?
I am using form to send email after submiting , I am just learning new concepts and real time validation is one of the good practice thats why I am trying this functionality