validating using onblur and onsubmit - javascript

I would like to know how to validate a form when I use the onblur handler and the onsubmit handler at the same time. I've tried to do it and it goes straight to the submit page without displaying an error message.
Because I also have radio buttons and checkboxes, how do I validate these if the user didn't click the radio button and exclude the checkbox from validation.
Thank You
function IsNotBlank(tf, tfHelp) {
var value = tf.value;
if (value == " ") {
tf.className = "invalid ";
tfHelp.innerHTML = "This field can 't be blank.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckLetters(tf, tfHelp) {
//check empty field from previous function.
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false) {
return false;
}
//assign field value
var value = tf.value;
//check if there is numbers.
var regex = new RegExp(/^[A-Za-z]{5,18}$/);
var testResult = regex.test(value);
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Use letters only and lengths must be between 5 and 18 characters.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckPhNumber(tf, tfHelp) {
//check empty field
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false)
return false;
var value = tf.value;
//validate phone number.
var regex = /^\d{8,10}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a valid phone number.";
return false;
} else {
tf.ClassName = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckEmail(tf, tfHelp) {
//check empty field
NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false) {
return false;
}
var value = tf.value;
//validate email address
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a valid email address.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckPostCode(tf, tfHelp) {
//check empty field
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false)
return false;
var value = tf.value;
//validate postcode.
var regex = /^\d{4}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a 4 digit post code.";
return false;
} else {
tf.ClassName = "valid";
tfHelp.innerHTML = "";
return false;
}
}
function ValidateForm(form) {
var formCheck = true;
for (var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
//alert(form.elements[i]);
if (e.onblur) {
// alert(e.onblur());
formCheck = e.onblur() && formCheck;
}
}
return formCheck;
}
function ResetForm(form) {
//select input elements and change color back to default
var arrayInputs = document.getElementsByTagName("input");
for (var i = 0; i < arrayInputs.length; i++) {
arrayInputs[i].className = "valid";
}
//clear text on span elements
var arraySpans = document.getElementsByTagName('span ');
for (var i = 0; i < arraySpans.length; i++) {
arraySpans[i].innerHTML = "";
}
}
<form action="submit.html" onreset="ResetForm()" onsubmit="ValidateForm(this);">
<div>
<label for="fname" class="label">First Name:</label>
<input class="valid" type="text" id="txtFname" onblur="return CheckLetters(this, txtFnameHelp);" />
<span id="txtFnameHelp"></span>
</div>
<div class="one">
<label for="lname" class="label">Last Name:</label>
<input class="valid" name="lname" id="txtLname" type="text" onblur="return CheckLetters(this, txtLnameHelp);" />
<span id="txtLnameHelp"></span>
</div>
<div class="one">
<label class="label" for="phone">Phone Number:</label>
<input class="one" id="txtPhone" type="text" onblur="CheckPhNumber(this, txtPhoneHelp);"><br>
<span id="txtPhoneHelp"></span>
</div>
<div class="one">
<label for="email" class="label">Email Address:</label>
<input class="valid" id="txtEmail" type="text" onblur="CheckEmail(this, txtEmailHelp)">
<span id="txtEmailHelp"></span><br>
</div>
<div class="one">
<label class="label">Post Code:</label>
<input id="txtPostcode" type="text" onblur="CheckPostCode(this, txtPostCodeHelp);"> <br>
<span id="txtPostCodeHelp"></span>
</div>
<br>
<div>
<label>Prefered Contact Method</label><br>
</div>
<div class="one">
</--<input type="radio" name="contact" value="email">Email
</-- <input type="radio" name="contact" value="phone">Phone
</div>
<br>
<div class="one">
<label>Your Message:</label><br />
<textarea id="txtMessage" rows="8" cols="40" onblur="IsNotBlank(this, txtMessageHelp)">Your Message</textarea>
<span id="txtMessageHelp"></span>
<br><br>
</div>
</--<input class="one" type="checkbox" name="newsletter" value="subscribe">I would like to subscribe to the newsletter <br>
<div>
<input class="one" type="submit" value="Send">
<input class="one " type="Reset " value="Clear">
<br><br>
</div>
</form>
Note that these type of JavaScript code can only be debugged using Microsoft Visual Studio for some reason and would not work on using legacy text editors.

You can use below concept to perform the both action and use window.addEventListener('DOMContentLoaded'function(e) {}) to check the validation
var error_user_name = false;
function checkpw(ele, e){
var user_name = document.forms["joinform"]["user_name"].value;
if (user_name == null || user_name == "") {
text = "UserName : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_name = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_name = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_name == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) { document.getElementById('user_name').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="text" name="user_name" id="user_name" placeholder="User_Name"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>

Related

function which should display an error message does not display it

As stated in the title, I have a function which should display an error message, but doesn't. I get an error:
Cannot set property 'textContent' of null
So basically, when a person clicks a check button, the input fields get a required "status". Once that happens, and error should appear underneath the input fields stating that they are required and should be filled out.
This does not happen (Cannot set property 'textContent' of null).
Any help would be welcome.
innerHTML of null error: pnameError.innerHTML = '';
textContent of null error: pnameError.textContent = 'You need to insert your name.';
JS
let pname = document.getElementById("popupfname");
let pnameError = document.querySelector("#popupfname + span#pf");
let pemail = document.getElementById("popupemail");
let pemailError = document.querySelector("#popupemail + span#pe");
var adverts = document.querySelector("input[name=advertsM]");
adverts.addEventListener('change', function() {
if (this.checked) {
console.log("CHECKED");
document.getElementById("popupfname").required = true;
document.getElementById("popupemail").required = true;
/* Prikaži error msg iz prve */
showNameError();
showEmailError();
} else {
console.log("NOT");
document.getElementById("popupfname").required = false;
document.getElementById("popupemail").required = false;
popfn();
popem();
}
});
function popfn (event) {
if (pname.validity.valid) {
pnameError.innerHTML = '';
pnameError.className = 'error'; //
} else {
showNameError();
}
};
function popem (event) {
if (pemail.validity.valid) {
pemailError.innerHTML = '';
pemailError.className = 'error';
} else {
showEmailError();
}
};
function showNameError() {
if (pname.validity.valueMissing) {
pnameError.textContent = 'You need to insert your name.';
} else if (pname.validity.typeMismatch) {
pnameError.textContent = 'Entered value must a name.';
} else if (pname.validity.tooShort) {
pnameError.textContent = 'Entered name must be atleast 3 characters long.';
}
pname.className = 'error active';
}
function showEmailError() {
if (pemail.validity.valueMissing) {
pemailError.textContent = 'You need to insert your e-mail address.';
} else if (pemail.validity.typeMismatch) {
pemailError.textContent = 'Entered value must be a valid e-mail address.';
} else if (pemail.validity.tooShort) {
pemailError.textContent = 'Entered e-mail address must be atleast 6 characters long.';
}
pemail.className = 'error active';
}
HTML
<form accept-charset="UTF-8" name="popupform" onsubmit="return false;" method="post" id="popupform">
<div id="adv-t"></div><br />
<label class="mlist">
<input type="checkbox" name="advertsM" id="advertsM" value="Yes">
<span id="adv-c"></span>
<br />
</label><br />
<input type="text" pattern="[A-Za-z][^0-9]{2,25}" name="popupfname" id="popupfname" placeholder="Janez"autocorrect="off" autocapitalize="off" /><br />
<span id="pf" class="error pfn" aria-live="polite"></span><br />
<input type="email" name="popupemail" id="popupemail" autocorrect="off" autocapitalize="off" maxlength="45" placeholder="moj#email.si"/><br />
<span id="pe" class="error pem" aria-live="polite"></span><br /><br />
<div id="small">
</div>
<hr style="margin-top: -6px;">
<button id="allow">
<span id="a"></span>
</button>
<button id="deny" onclick="deny()">
<span id="d"></span>
</button>
</form>
The problem is the next element to input is br, not a span
change
let pnameError = document.querySelector("#popupfname + span#pf")
...
let pemailError = document.querySelector("#popupemail + span#pe");
to
let pnameError = document.querySelector("#popupfname + br + span#pf")`
...
let pemailError = document.querySelector("#popupemail + br + span#pe");
Working example:
let pname = document.getElementById("popupfname");
let pnameError = document.querySelector("#popupfname + br + span#pf"); // <-- here ou had an error, because the next element to #popupfname is br, but not the span id="pf"
let pemail = document.getElementById("popupemail");
let pemailError = document.querySelector("#popupemail + br + span#pe"); // <-- here ou had an error, because the next element to #popupemail is br, but not the span id="pe"
var adverts = document.querySelector("input[name=advertsM]");
adverts.addEventListener( 'change', function() {
if(this.checked) {
console.log("CHECKED");
document.getElementById("popupfname").required = true;
document.getElementById("popupemail").required = true;
/* Prikaži error msg iz prve */
showNameError();
showEmailError();
} else {
console.log("NOT");
document.getElementById("popupfname").required = false;
document.getElementById("popupemail").required = false;
popfn();
popem();
}
});
function popfn (event) {
if (pname.validity.valid) {
pnameError.innerHTML = '';
pnameError.className = 'error'; //
} else {
showNameError();
}
};
function popem (event) {
if (pemail.validity.valid) {
pemailError.innerHTML = '';
pemailError.className = 'error';
} else {
showEmailError();
}
};
function showNameError() {
if(pname.validity.valueMissing){
pnameError.textContent = 'You need to insert your name.';
}else if(pname.validity.typeMismatch){
pnameError.textContent = 'Entered value must a name.';
}else if(pname.validity.tooShort){
pnameError.textContent = 'Entered name must be atleast 3 characters long.';
}
pname.className = 'error active';
}
function showEmailError() {
if(pemail.validity.valueMissing){
pemailError.textContent = 'You need to insert your e-mail address.';
}else if(pemail.validity.typeMismatch){
pemailError.textContent = 'Entered value must be a valid e-mail address.';
}else if(pemail.validity.tooShort){
pemailError.textContent = 'Entered e-mail address must be atleast 6 characters long.';
}
pemail.className = 'error active';
}
<form accept-charset="UTF-8" name="popupform" onsubmit="return false;" method="post" id="popupform">
<div id="adv-t"></div><br />
<label class="mlist">
<input type="checkbox" name="advertsM" id="advertsM" value="Yes">
<span id="adv-c"></span>
<br />
</label><br />
<input type="text" pattern="[A-Za-z][^0-9]{2,25}" name="popupfname" id="popupfname" placeholder="Janez"autocorrect="off" autocapitalize="off" /><br />
<span id="pf" class="error pfn" aria-live="polite"></span><br />
<input type="email" name="popupemail" id="popupemail" autocorrect="off" autocapitalize="off" maxlength="45" placeholder="moj#email.si"/><br />
<span id="pe" class="error pem" aria-live="polite"></span><br /><br />
<div id="small">
</div>
<hr style="margin-top: -6px;">
<button id="allow">
<span id="a"></span>
</button>
<button id="deny" onclick="deny()">
<span id="d"></span>
</button>
</form>

Javascript onsubmit is not returning any value like true or false. Form can submit without validation

I am developing in my final year school project. Now I faced a problem. Some of the onsubmit function in my forms are not functioning well.
The problem is:
I am validating the details filled in in the form. But although the innerHTML already pointed out the wrong by using getElementById, the form still can be submitted. How to stop the form from submitting?
The function does not return any true or false value.
I've already checked through the code. But I can't find the mistakes.
I tried to change the function validate() to window.validate = function(), it does not work well either.
I tried to change the validate function to only return false. The form is still submitting.
I tried event preventDefault but the outcomes become I cannot submit the form.
Javascript part
function check_location() {
var user_address = document.getElementById("location");
var user_address_mess = document.getElementById("addressvalidate");
var checkaddress;
if (user_address.value == "") {
//.....
return false;
} else if (user_address.value.length <= 10) {
//.....
return false;
} else {
//....
return true;
}
}
function check_stime() {
var starttime = document.getElementById("starttime");
var mess_starttime = document.getElementById("mess_starttime");
var check1;
if (starttime != null) {
if (starttime.value == "") {
//...
return false;
}
else if (starttime.value < "08:00" && starttime > "19:00") {
//...
return false;
}
else {
//...
return true;
}
}
}
function check_date() {
today = new Date();
today.setDate(today.getDate() + 14);
var eventdate = document.getElementById("date").value;
eventdate1 = new Date(eventdate);
var mess_date = document.getElementById("mess_date");
var check2;
if (document.getElementById("checkdate") != null) {
var checkdate = document.getElementById("checkdate").innerHTML;
}
if (eventdate != null) {
if (eventdate.value == "") {
//...
return false;
}
else if (eventdate1 <= today) {
//...
return false;
}
else {
//...
return true;
}
}
}
function check_etime() {
var starttime = document.getElementById("starttime");
var endtime = document.getElementById("endtime");
var mess_endtime = document.getElementById("mess_endtime");
var eventdate = document.getElementById("eventdate");
var check3;
if (endtime != null) {
if (endtime.value == "") {
// ...
return false;
}
else if (endtime.value == starttime.value || endtime.value <= starttime.value) {
// ...
return false;
}
else if (endtime.value <= starttime.value && eventdate.value <= fulldate) {
// ...
return false;
}
else if (endtime.value < "09:00" && endtime.value > "22.00pm") {
// ...
return false;
}
else {
//...
return true;
}
}
}
function validate() {
checkstime = check_stime();
checketime = check_etime();
checkdate = check_date();
checklocation = check_location();
if (checklocation == false || checkstime == false || checketime == false || checkdate == false) {
return false;
} else {
return true;
}
}
HTML Part
<div class="g-text-center--xs g-margin-b-40--xs">
<h2 class="g-font-size-30--xs g-color--black">Booking Form</h2>
</div>
<br>
<form autocomplete="off" name="form_submit" onsubmit=" return validate();" method="post" action="">
<div class="g-margin-b-30--xs">
<p><b>Package Name :</b>
<input type="text" name="pname" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" value="<?php echo $pack1['package_name']?>" style="width:200px; font-weight:bold; color:black;" disabled>
</p>
</div>
<div class="g-margin-b-30--xs">
<p><b>Package Price :</b>
<input type="text" name="pprice" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" value="RM <?php echo $pack1['package_price']?>" style="width:200px; font-weight:bold; color:black;" disabled>
</p>
</div>
<div class="g-margin-b-30--xs">
<b>Event Date :</b>
<input onfocusout="check_date()" name="date" id="date" type="date" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" style="width:400px; color:black;">
<span id="mess_date" style="color:red;font-weight:normal;"></span>
</div>
<div class="g-margin-b-30--xs">
<b>Start Time :</b>
<input onfocusout="check_stime()" name="starttime" id="starttime" type="time" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" style="width:500px;" />
<span id="mess_starttime" style="color:red;font-weight:normal;"></span>
</div>
<div class="g-margin-b-30--xs">
<b>End Time :</b>
<input onfocusout="check_etime()" name="endtime" id="endtime" type="time" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" style="width:500px;" />
<span id="mess_endtime" style="color:red;font-weight:normal;"></span>
</div>
<b>Event Location : </b>
<br>
<textarea class="form-control s-form-v2__input" name="location" id="location" style=" width:500px; font-weight:bold; text-align:left;" onfocusout="check_location()"></textarea>
<span style="color:red;font-weight:normal;" id="addressvalidate"></span>
<div class="g-text-center--xs">
<br>
<button style="margin-bottom:50px;" type="submit" id="submit" name="addtocart" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Submit</button>
<div class="clearfix"> </div>
</div>
</form>
I want to prevent the form from submitting when there is something wrong.
You can easily fix this by changing your code to this.
<form id="myForm" onsubmit="event.preventDefault(); validate();">
and change validate() javascript function to this.
function validate() {
checkstime = check_stime();
checketime = check_etime();
checkdate = check_date();
checklocation = check_location();
if (checklocation == false || checkstime == false || checketime == false || checkdate == false) {
return false;
} else {
document.getElementById("myForm").submit();
}
}
On click of the submit button add something like below
<button onclick="return validate()" style="margin-bottom:50px;" type="submit" id="submit" name = "addtocart" class = "btn btn-primary"><span class = "glyphicon glyphicon-floppy-disk"></span> Submit</button>
In the validate() function ,you if you return true it will submit,if you return false, it will not submit form,there you can show the error message
Remove everything from the form tag all the submit lines and simply give it a unique id and same goes to the button tag too something like this
<form id ="my_form" action="/action_page.php">
<button id="u_id">submit</button>
</form>
Then in java script part
var form = document.getElementById("my_form");
document.getElementById("u_id").addEventListener("click", function () {
checkstime = check_stime();
checketime = check_etime();
checkdate = check_date();
checklocation = check_location();
if (checklocation == false || checkstime == false || checketime == false || checkdate == false) {
//show error msg
} else {
form .submit();
}
});

How do I get my form to use new information after errors are corrected?

I'm search but i'm not 100% how you get this to resubmit, using new information, I've got all the errors up and showing as appropriate, but in terms of, how to hit the submit button again, and then it reassesses the form; how do i go about this? Any help would be appreciated.
html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>RATool</title>
<link rel="stylesheet" type="text/css" href="cfcss.css">
<script src="cf.js"></script>
</head>
<body>
<h1> Health Authority </h1>
<h2> Contact Form </h2>
<form>
<fieldset>
<label for="fname">First Name:</label>
<input name="fname" id="fname" class="formfield" type="text">
<span id="errfname" class="error">*This is required</span>
<span id="errfname1" class="error">*Name fields must have more than one character, and do not contain numbers
or other non-allowed alphabetic characters. The only character the last name
field should legitimately contain is a hyphen (e.g. Whittaker-Jones).</span>
<span id="errfname2" class="error">*This can only contain alphabetic numbers and if desired, one hyphen</span>
<br>
<label for="sname">Surname:</label>
<input name="sname" id="sname" class="formfield" type="text">
<span id="errsname" class="error">*This is required</span>
<span id="errsname1" class="error">*Name fields must have more than one character, and do not contain numbers
or other non-allowed alphabetic characters. The only character the last name
field should legitimately contain is a hyphen (e.g. Whittaker-Jones).</span>
<span id="errsname2" class="error">*This can only contain alphabetic numbers and if desired, one hyphen</span>
<br>
<label for="title">Title: </label>
<select name="title" id="title">
<option value="Please select">Please select</option>
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
<option value="Mrs.">Mrs.</option>
<option value="Miss.">Miss.</option>
<option value="Master.">Master.</option>
</select>
<span id="errtitle" class="error">*This is required</span>
<br>
<br>
<br>
<label for="HANo">Health Authority Number:</label>
<input name="HANo" id="HANo" class="formfield"type="text">
<span id="errHANo" class="error">*This is required</span>
<span id="errHANo2" class="error">*This must be in format ZHA123456 (ZHA followed by 6 numbers)</span>
<br>
<br>
<label for="email">Email:</label>
<input name="email" id="email" class="formfield"type="text">
<span id="erremail" class="error">*This is required</span>
<span id="erremail2" class="error">*Please enter a valid email</span>
<br>
<br>
<br>
<label for="telno">Telephone Number:</label>
<input name="telno" id="telno" class="formfield" type="text">
<span id="errtelno" class="error">* If a telephone number is entered, then it should contain only numbers, not
letters, or other disallowed characters. A valid Zedland telephone number has
11 digits (no spaces)</span>
<span id="errtelno1" class="error">*This must just be numbers</span>
<br>
<button onclick="checkForm()">Submit</button>
</fieldset>
</form>
</body>
</html>
javascript
function checkForm(){
var errors=document.getElementsByClassName('error');
for(var i=0;i<errors.length;i++){
errors[i].style.display='none';
}
if (document.getElementById("fname").value == "" ) {
document.getElementById("errfname").style.display = "inline";
document.getElementById("errfname").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("fname").value.length < 2 ) {
document.getElementById("errfname1").style.display = "inline";
document.getElementById("errfname1").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("fname").value.length > 1) {
checkFName();
e.preventDefault();
}
if (document.getElementById("sname").value == "" ) {
document.getElementById("errsname").style.display = "inline";
document.getElementById("errsname").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("sname").value.length < 2 ) {
document.getElementById("errsname1").style.display = "inline";
document.getElementById("errsname1").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("sname").value.length > 1) {
checkSName();
e.preventDefault();
}
if (document.getElementById("title").value == "Please select" ) {
document.getElementById("errtitle").style.display = "inline";
document.getElementById("errtitle").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("HANo").value == "" ) {
document.getElementById("errHANo").style.display = "inline";
document.getElementById("errHANo").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("HANo").value.length > 0) {
if (checkHANo());
e.preventDefault();
}
if (document.getElementById("email").value == "" ) {
document.getElementById("erremail").style.display = "inline";
document.getElementById("erremail").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("email").value.length > 0 ) {
if(checkEmail());
e.preventDefault();
}
if (document.getElementById("telno").value.length != 11 ) {
document.getElementById("errtelno").style.display = "inline";
document.getElementById("errtelno").style.visibility = "visible";
e.preventDefault();
}
if (document.getElementById("telno").value == /^\d+$/ ) {
document.getElementById("errtelno1").style.display = "inline";
document.getElementById("errtelno1").style.visibility = "visible";
e.preventDefault();
}
}
function checkEmail(){
var email = document.getElementById('email');
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
document.getElementById("erremail2").style.display="inline";
document.getElementById("erremail2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
function checkHANo(){
var HANo = document.getElementById("HANo");
var hanoRegEx = /[ZHA]\d{6}/;
if (!hanoRegEx.test(HANo.value)) {
document.getElementById("errHANo2").style.display = "inline";
document.getElementById("errHANo2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
function checkFName(){
var first = document.getElementById("fname");
var firstRegEx = /^[a-zA-Z-]{2,40}$/;
if (!firstRegEx.test(first.value)){
document.getElementById("errfname2").style.display = "inline";
document.getElementById("errfname2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
function checkSName(){
var sec = document.getElementById("sname");
var secRegEx = /^[a-zA-Z-]{2,40}$/;
if (!secRegEx.test(sec.value)){
document.getElementById("errsname2").style.display = "inline";
document.getElementById("errsname2").style.visibility = "visible";
return true;
}
e.preventDefault();
}
Your error messages are displaying by default. To hide those add the CSS class below:
.error{ display:none; }
Add this piece of code at the beginning of checkForm() to re-hide the message when error is corrected. Eg:
var errors=document.getElementsByClassName('error');
for(var i=0;i<errors.length;i++){
errors[i].style.display='none';
}
Instead of calling the formCheck() function on onclick of the button, call it onsubmit of the form with a return. Like
<form method="post" action="yourpage" onsubmit="return checkForm()">
To show all errors, declare a variable with default value as true like var isValid=true; just above/below the for loop
Eg:
function checkForm(){
var isValid = true;
var errors=document.getElementsByClassName('error');
for(var i=0;i<errors.length;i++){
errors[i].style.display='none';
}
if (document.getElementById("fname").value == "" ) {
document.getElementById("errfname").style.display = "inline";
document.getElementById("errfname").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("fname").value.length < 2 ) {
document.getElementById("errfname1").style.display = "inline";
document.getElementById("errfname1").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("fname").value.length > 1) {
isValid = checkFName();
}
if (document.getElementById("sname").value == "" ) {
document.getElementById("errsname").style.display = "inline";
document.getElementById("errsname").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("sname").value.length < 2 ) {
document.getElementById("errsname1").style.display = "inline";
document.getElementById("errsname1").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("sname").value.length > 1) {
isValid = checkSName();
}
if (document.getElementById("title").value == "Please select" ) {
document.getElementById("errtitle").style.display = "inline";
document.getElementById("errtitle").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("HANo").value == "" ) {
document.getElementById("errHANo").style.display = "inline";
document.getElementById("errHANo").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("HANo").value.length > 0) {
isValid = checkHANo();
}
if (document.getElementById("email").value == "" ) {
document.getElementById("erremail").style.display = "inline";
document.getElementById("erremail").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("email").value.length > 0 ) {
if(checkEmail());
isValid = false;
}
if (document.getElementById("telno").value.length != 11 ) {
document.getElementById("errtelno").style.display = "inline";
document.getElementById("errtelno").style.visibility = "visible";
isValid = false;
}
if (document.getElementById("telno").value == /^\d+$/ ) {
document.getElementById("errtelno1").style.display = "inline";
document.getElementById("errtelno1").style.visibility = "visible";
isValid = false;
}
return isValid;
}
NOTE: You have to return false from other functions such as checkEmail(),checkHANo() also if there is error. It seems you are returning only true. And remove all e.preventDefault()
That's it

Validating Input with Javascript

I'm working on a web form with several textboxes and a submit button. When the submit button is clicked, I am supposed to verify that the required fields all have input and that the age field is only numeric. For example, the user can enter 56, but 56 years-old, shouldn't be accepted. If the user enters invalid input or leaves required fields blank, the border around the appropriate textboxes should turn red.
However, as my code is written now all the required fields turn red regardless of input. Any ideas how I can fix this and make the page follow the couple of rules I listed?
Most Recent Code
<html>
<head>
<title>Project 4</title>
<style type="text/css">
body {
background-color: black;
color: blue;
text-align: center;
border: 2px double blue;
}
</style>
</head>
<body>
<h1>Welcome to my Web Form!</h1>
<p>
Please fill out the following information.<br>
Please note that fields marked with an asterisk (*) are required.
</p>
<form name="myForm" id="myForm" onsubmit="return validateForm()">
*Last Name: <br>
<input type="text" id="lastname">
<br>
First Name: <br>
<input type="text" id="firstname">
<br>
*Hobbies (separate each hobby with a comma): <br>
<input type="text" id="hobbies">
<br>
Pets:
<div id="petsContainer">
<input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
</div>
<br>
Children:
<div id="childContainer">
<input type="text" id="children">
<input type="button" id="addKid" value="Add Child">
</div>
<br>
*Address: <br>
<input type="text" id="address">
<br>
*Phone Number:<br>
<input type="text" id="phone">
<br>
*Age: <br>
<input type="text" id="age">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var validatePhoneOnKeyUpAttached = false;
var validateLNameOnKeyUpAttached = false;
var validateHobbiesOnKeyUpAttached = false;
var validateAddressOnKeyUpAttached = false;
var validateAgeOnKeyUpAttached = false;
function validateForm() {
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
else if(!validateLNameOnKeyUpAttached) {
document.getElementById("lastname").onkeyup = checkEmpty;
validateLNameOnKeyUpAttached = true;
}
else if(!validateHobbiesOnKeyUpAttached) {
document.getElementById("hobbies").onkeyup = checkEmpty;
validateHobbiesOnKeyUpAttached = true;
}
else if(!validateAddressOnKeyUpAttached) {
document.getElementById("address").onkeyup = checkEmpty;
validateAddressOnKeyUpAttached = true;
}
else if(!validateAgeOnKeyUpAttached) {
document.getElementById("age").onkeyup = checkEmpty;
document.getElementById("age").onkeyup = checkAge;
validateAgeOnKeyUpAttached = true;
}
return checkEmpty() && checkPhone() && checkAge();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").style.borderColor="red";
return false;
}
}
function checkEmpty() {
var lname = document.forms["myForm"]["lastname"].value;
var pNum = document.forms["myForm"]["phone"].value;
var hobs = document.forms["myForm"]["hobbies"].value;
var live = document.forms["myForm"]["address"].value;
var yr = document.forms["myForm"]["age"].value;
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("hobbies").style.borderColor = (hobs == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
document.getElementById("address").style.borderColor = (live == "") ? "red" : "transparent";
document.getElementById("age").style.borderColor = (yr == "") ? "red" : "transparent";
}
function checkAge() {
var age = document.getElementById("age").value;
if(isNan(age)) {
return false;
}
else {
document.getElementById("age").style.borderColor="red";
return true;
}
}
document.getElementById("addPet").onclick=function() {
var div = document.getElementById("petsContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "pats[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
document.getElementById("addKid").onclick=function() {
var div = document.getElementById("childContainer");
var input = document.createElement("input");
input.type = "text";
input.name = "child[]";
div.appendChild(document.createElement("br"));
div.appendChild(input);
}
</script>
</body>
</html>
The problem I'm currently having is that when I click the submit button, all the fields turn red for a split second, but then go back to the regular color and the input is erased. Any thoughts on how to fix this?
By including all of the borderColor="red" statements in a single code block, you're applying that style to all your inputs, even if only one of them failed validation. You need to separate out each statement so that it only applies to the individual field(s) that failed validation:
document.getElementById("lastname").style.borderColor = (lname == "") ? "red" : "transparent";
document.getElementById("phone").style.borderColor = (pNum == "") ? "red" : "transparent";
...
Also, I'm using the ternary operator ? : to clean up the code as well. These statements would replace the if-else block you've written.
I am using the following javascript functions in order to validate my form variables. Hope these will helpful for you.
var W3CDOM = (document.getElementsByTagName && document.createElement);
window.onload = function () {
document.forms[0].onsubmit = function () {
return validate()
}
}
function validate() {
validForm = true;
firstError = null;
errorstring = '';
var x = document.forms[0].elements;
for (var i = 0;i < x.length;i++) {
if (!x[i].value) {
validForm = false;
writeError(x[i], 'This field is required');
}
}
// This can be used to validate input type Email values
/* if (x['email'].value.indexOf('#') == -1) {
validForm = false;
writeError(x['email'],'This is not a valid email address');
}
*/
if (!W3CDOM)
alert(errorstring);
if (firstError)
firstError.focus();
return validForm;
}
function writeError(obj, message) {
validForm = false;
//if (obj.hasError) return false;
if (W3CDOM) {
obj.className += ' error';
obj.onchange = removeError;
var sp = document.createElement('span');
sp.className = 'error';
sp.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(sp);
obj.hasError = sp;
} else {
errorstring += obj.name + ': ' + message + '\n';
obj.hasError = true;
}
if (!firstError)
firstError = obj;
return false;
}
function removeError() {
this.className = this.className.substring(0, this.className.lastIndexOf(' '));
this.parentNode.removeChild(this.hasError);
this.hasError = null;
this.onchange = null;
}
You can call the validations right after the form submission as given below.
<form name="loginForm" action="do.login" method="POST" class="form" onsubmit="return validate();">

.focus() after submit incorrect infos to a form, doesn't work

I have an easy form. When i submit the form with incorrect informations, the error message appear but i would that the first incorrect input is highlight with focus.
I think how i use .focus() is right but it might doesn't fit with the rest of the function.
Here my code:
<form name="login-registration" onSubmit="return validateForm()" method="post" action="" novalidate >
<div class="span-4">
<label>Email</label>
<label>Your password</label>
<label>Repeat password</label>
<label> <input class="inline check" type="checkbox" id="policy" name="policy" value="policy" /> I agree</label>
</div>
<div class="span-4">
<input type="email" name="emailinput" id="emailinput" value = "<?php echo htmlspecialchars($_POST['emailinput']); ?>"/>
<input type="password" name="pswinput" id="pswinput" value=""/>
<input type="password" name="pswrepeatinput" id="pswrepeatinput" value="" onblur="isValidPswRep()"/>
<input type="submit" name="submit" value="Login" />
</div>
<div class="span-4">
<p id="emptyEmail" class="hidden">Email field is required</p>
<p id="invalidEmail" class="hidden">Email you insert is invalid!</p>
<p id="pswMinMax" class="hidden">Password should be from 4 to 8 caracters</p>
<p id="pswLettNum" class="hidden">Password should be letters and numbers. No special caracters are allow</p>
<p id="pswR" class="hidden">Your passwords is different</p>
<p id="checkN" class="hidden">You must agree to our term</p>
</div>
</form>
And here the script:
function validateForm(){
var email = document.getElementById("emailinput").value;
var psw = document.getElementById("pswinput").value;
var pswrep = document.getElementById("pswrepeatinput").value;
var check = document.getElementById("policy");
if (isValidEmail(email)){
if(isValidPsw(psw,4,8)){
if(isValidPswRep(pswrep)){
if(isValidCheckbox(check)){
return true;
}
}
}
}
return false;
}
function isValidEmail(email) {
var validCharacters = /^\w+#\w+\.\w+$/;
if(email == ""){
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "error";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "hidden";
return false;
email.focus();
} else if(!validCharacters.test(email)) {
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "hidden";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "error";
return false;
email.focus();
} else {
var emailErr = document.getElementById("emptyEmail");
emailErr.className = "hidden";
var emailErr2 = document.getElementById("invalidEmail");
emailErr2.className = "hidden";
return true;
}
}
function isValidPsw(psw, minLen, maxLen) {
var lengthPsw = psw.length;
var lettNum = /^[0-9a-zA-Z]+$/;
if(lengthPsw == 0 || lengthPsw <= minLen || lengthPsw > maxLen){
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "error";
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "hidden";
return false;
psw.focus();
} else if(!lettNum.test(psw)){
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "error";
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "error";
return false;
psw.focus();
} else {
var pswErr = document.getElementById("pswMinMax");
pswErr.className = "hidden";
var pswErr2 = document.getElementById("pswLettNum");
pswErr2.className = "hidden";
return true;
}
}
function isValidPswRep(pswrep){
var psw = document.getElementById("pswinput").value;
var pswrep = document.getElementById("pswrepeatinput").value;
if(pswrep != psw){
var pswRepErr = document.getElementById("pswR");
pswRepErr.className = "error";
return false;
pswrep.focus();
}
var pswRepErr = document.getElementById("pswR");
pswRepErr.className = "hidden";
return true;
}
function isValidCheckbox(check){
if (!check.checked){
var checkErr = document.getElementById("checkN");
checkErr.className = "error";
return false;
check.focus();
}
var checkErr = document.getElementById("checkN");
checkErr.className = "hidden";
return true;
}

Categories