Why do I have to submit 2 times for the validation to work?

I need to submit 2 times for the validation to work. Can't figure out why!  Any advice?
-------------------------------------

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script language="JavaScript">
<!--

function checkFormEntry() {

if (document.getElementById("TxtName").value == "")
	{
	document.getElementById("TxtName").setCustomValidity("Please insert your name");
	return false;
	}
	
if (document.getElementById("TxtSurname1").value == "" && document.getElementById("TxtSurname2").value == "")
	{
	document.getElementById("TxtSurname1").setCustomValidity("Please insert at least one surname ");
	return false;
	}

if (document.getElementById("Txt_Landline").value == "" && document.getElementById("Txt_LMobile1").value == "" && document.getElementById("Txt_LMobile2").value == "")
	{
	document.getElementById("Txt_Landline").setCustomValidity("Please provide at least one contact telephone number.");
	return false;
	}
if (document.getElementById("txtEmail").value==""){
		document.getElementById("txtEmail").setCustomValidity("Please insert your email");
		return false;
	}
if (echeck(document.getElementById("txtEmail").value)==false){
		document.getElementById("txtEmail").value=""
		document.getElementById("txtEmail").focus();
		return false;
	}
}

function echeck(str) {
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		document.getElementById("txtEmail").setCustomValidity("The email you entered is invalid ");
		return false;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		document.getElementById("txtEmail").setCustomValidity("The email you entered is invalid ");
		return false;
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		document.getElementById("txtEmail").setCustomValidity("The email you entered is invalid ");
		return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		document.getElementById("txtEmail").setCustomValidity("The email you entered is invalid ");
		return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		document.getElementById("txtEmail").setCustomValidity("The email you entered is invalid ");
		return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		document.getElementById("txtEmail").setCustomValidity("The email you entered is invalid ");
		return false;
		 }
		
		 if (str.indexOf(" ")!=-1){
		document.getElementById("txtEmail").setCustomValidity("The email you entered is invalid ");
		return false;
		 }
 		 return true					
}
//-->
</script>

</head>

<body>

	<form name="form_Dyno" id="form_Dyno" action="..." method="post" onsubmit = "return checkFormEntry(this)">

		<div class="JS_Form_Unit">
			<input type="text" name="TxtName" id="TxtName" placeholder="Name" oninput="setCustomValidity('')"/>
			<input type="text" name="TxtSurname1" id="TxtSurname1" placeholder="Surname1" oninput="setCustomValidity('')"/>
			<input type="text" name="TxtSurname2" id="TxtSurname2" placeholder="Surname2" oninput="setCustomValidity('')"/>
		</div>
		<div class="JSl_FrmText2"> 
			<input type="submit">
		</div>

	</form>

</body>
</html>

Open in new window

LVL 5
Abiel de GrootDeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Snarf0001Commented:
You have the validation flow a little bit confused.

The little tooltip that pops up actually saying "Please insert your name" is actually once the browser has taken over for you.
If you put a breakpoint in your "checkFormEntry" method, you'll see it only actually gets hit the first time.

1) Press submit
2) checkFormEntry called, sets TxtName to invalid state, "return false" stopping the form submission.
3) Press submit again
4) The browser now KNOWS that TxtName is invalid as per the previous call, so it never even tries to submit the form, and shows the user the error.  No breakpoint hit, checkFormEntry is never even called.


You should really be calling .setCustomValidity on change of every element, so once the user tries to submit the form, it already knows if the element is in an invalid state or not.

That make sense?
0
Abiel de GrootDeveloperAuthor Commented:
Hmm ... sort of :-) but not clearly. I know that setCustomValidity I can set a rex exp or validation rule for each element but it's not as diverse as using a Javascript. What is my best way out?

Many thanks for your advice

A
0
Snarf0001Commented:
When you use the built-in validation attributes, the entire system is actually incredibly robust.

<input type="text" required maxlength="25" pattern="^[a-zA-Z]$" />

Open in new window


The line above will stop form submission unless:
1) It has a value (required)
2) It's not longer than 25 characters (maxlength)
3) It's only letters

By applying the "pattern" attribute, you can specify any regex to enforce on the element.
And you don't need a line of javascript to run this, the browsers handle it (except for polyfill if it's an archaic browser).

This will just use generic messaging though.   If you need to use something custom, follow something like this as an example.
Add the validation tags as necessary (required, maxlength, min, max, pattern....)
Add a custom data attribute for the error message (data-error in this example).  Set a generic handler for the "invalid" event on all elements with a custom message.
The "invalid" will fire whenever the browser picks up an invalid value, based on the required / pattern or other validation attributes you use, and THEN use .setCustomValidity only to customize the message being shown.
Also handle "onchange", so the browser has a chance to pickup valid / invalid items again.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    <script>
        window.onload = function (e) {

            var inputs = document.querySelectorAll("input[data-error]");
            for (var i = 0; i < inputs.length; i++) {
                inputs[i].addEventListener("invalid", function (e) {
                    this.setCustomValidity(this.getAttribute("data-error"));
                });
                inputs[i].addEventListener("change", function (e) {
                    this.setCustomValidity("");
                });
            }
        };
    </script>
</head>
<body>
    <form name="form_Dyno" id="form_Dyno" action="..." method="post" onsubmit="return checkFormEntry(this)">

        <div class="JS_Form_Unit">
            <input type="text" name="TxtName" id="TxtName" placeholder="Name" required data-error="Please insert your name" />
            <input type="text" name="TxtSurname1" id="TxtSurname1" placeholder="Surname1" required data-error="Please insert at least one surname" />
            <input type="text" name="TxtSurname2" id="TxtSurname2" placeholder="Surname2" />

            <!-- the type email will enforce basic email constraints, but still not perfect.  You can also supply an additional regex with tighter restrictions on the format if needed -->
            <input type="email" name="TxtEmail" id="TxtEmail" placeholder="Email" data-error="Email is invalid" />
        </div>
        
        <div class="JSl_FrmText2">
            <input type="submit">
        </div>
        
    </form>
</body>
</html>

Open in new window


Again, the above JS is required ONLY to show a custom message.  If you take the entire script block out, the browser will still stop the form submission the same way, will just show generic messages for what's incorrect.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Abiel de GrootDeveloperAuthor Commented:
Many thanks Snarf0001 :-)

I really appreciate your help.

A
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
HTML

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.