JavaScript display multiple error message form submission? - javascript

What am I doing wrong in my JavaScript? I would like to display an error message if a user forgets to type in any of my HTML form fields. I would like to create an error message for the name, email, and phone number fields. Even if a user puts in their name, I would like error messages for the remainder 2, or remainder 1, or no error messages. I have attached my JavaScript code below. Thank you for those who help.
function validateForm() {
var ret = true;
var name = document.forms["contactform"]["name"].value;
if (name == "") {
document.getElementById('error').innerHTML = "Please enter your name";
ret = false;
}
var email = document.forms["contactform"]["email"].value;
if (email == "") {
document.getElementById('erroremail').innerHTML = "Please enter your email";
ret = false;
}
var phone = document.forms["contactform"]["phone"].value;
if (phone == "") {
document.getElementById('errorphone').innerHTML = "Please enter your phone";
ret = false;
}
return ret;
}

If you want separate error display for each input you could just add else with empty innerHTML.
Something like this:
var name = document.forms["contactform"]["name"].value;
var nameError = document.getElementById('error');
if (name == "") {
nameError.innerHTML = "Please enter your name";
ret = false;
} else {
nameError.innerHTML = "";
}
Full example here: https://jsfiddle.net/1h1tkh7y/

Create a variable called something like :
var fieldsInError = "";
Then in your validation in each check if it fails validation add the field:
fieldsInError += "name," (or whatever the field is)
Then at the end of the function update your error field with something like:
document.getElementById('error').innerHTML = "Please enter " + fieldsInError.substring(0, fieldsInError.length-1);
So your function would look something like this:
function validateForm() {
var fieldsInError = "";
var name = document.forms["contactform"]["name"].value;
if (name == "") {
fieldsInError += "name,"
}
var email = document.forms["contactform"]["email"].value;
if (email == "") {
fieldsInError += "email,"
}
var phone = document.forms["contactform"]["phone"].value;
if (phone == "") {
fieldsInError += "phone,"
}
if(fieldsInError != ""){
document.getElementById('error').innerHTML = "Please enter " + fieldsInError.substring(0, fieldsInError.length-1);
return false;
} else {
return true;
}
}

Related

Having trouble with the javascript file does not respond to html form

I'm trying to make a javascript file to check the rules of a registration form but the alert does not pop up so I don't know which part is not working.
When I click the submit button, It goes straight to the PHP file instead of listing messages in an alert window.
function validate() {
var name = document.getElementById("name").value;
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirm-password").value;
var genderM = document.getElementById("gender-male").checked; //radio
var genderF = document.getElementById("gender-female").checked; //radio
var temperature = document.getElementById("temperature").checked; //checkbox
var favourite = document.getElementById("favourite").checked; //select
var email = document.getElementById("email").value;
var errMsg = "";
var result = true;
if (name == "") {
errMsg += "Please enter a name.\n";
}
if (username == "") {
errMsg += "Please enter a username.\n";
}
if (password == "") {
errMsg += "Please enter a password.\n";
}
if (confirmPassword == "") {
errMsg += "Please re-enter password.\n";
}
if (password != confirmPassword) {
errMsg += "Confirm password does not match.\n";
}
if (email == "") {
errMsg += "Please enter an email address.\n";
}
if (email.indexof('#') == 0) {
errMsg += "Email address invalid.\n";
}
if (email.indexof('#') < 0) {
errMsg += "Email address must contain an # symbol.\n";
}
if ((genderM = "" )&&(genderF = "")) {
errMsg += "Please enter a gender.\n";
}
if (temperature == "") {
errMsg += "Please enter a drink temperature.\n";
}
if (favourite == "") {
errMsg += "Please enter a favourite drink.\n";
}
if (errMsg != "") {
alert (errMsg);
result = false;
}
return result;
}
function init() {
var register = document.getElementById("register"); //form id="register"
register.onsubmit = validate;
}
window.onload = init();
I tried to double check all the posibilities error like missing ";" or wrong elements, etc. However, not thing seems to work for me.
try this
window.onload = init // assign function instead of calling it

Regex not firing on user form

My Regex for email does not seem to be working, it does not fire,
the validation on the form passes even if the user only inputs a single .
here is my code:
var a = ["txtTitle", "txtSurname", "txtEmail", "txtPostCode"];
$.each(a, function (index, value) {
if (sMsg == "") {
if ($("#" + value).val().trim() == "") {
var sText = $('td:first', $($("#" + value)).parents('tr')).text();
sMsg = "Please enter a " + sText;
$("#" + value).focus();
}
}
});
if (sMsg == "") {
if ($("#txtPhone").val().trim() == "" && $("#txtMobile").val().trim() == "") {
sMsg = "Please enter a phone or mobile number";
$("#txtPhone").focus();
}
}
if (sMsg == "") {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!regex.test($("#txtEmail").val())) {
sMsg = "Please enter a valid email address";
}
}
break;
i have now resolved this, turns out there was a primary validation on the email field to check whether it contains a value, i simply removed this and it worked
amended this line:
var a = ["txtTitle", "txtSurname", "txtEmail", "txtPostCode"];
to
var a = ["txtTitle", "txtSurname","txtPostCode"];

Form Validation with a bit of elegance

Currently I have got the following code and I keep hearing that I should not use the alert function, it's old fashioned etc.
What else could I use instead of alert?
document.getElementById("practiseForm").onsubmit = function() {
if(document.getElementById("fname").value.trim() === ""){
alert("First Name Field Cannot Be Blank");
allowsubmit = false;
}
if(document.getElementById("lname").value.trim() === ""){
alert("Last Name Field Cannot Be Blank");
allowsubmit = false;
}
var email = document.getElementById('email');
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
alert("Invalid Email address");
return false;
}
}
Fiddle
I updated your fiddle to provide an example of inline error messages:
document.getElementById("practiseForm").onsubmit = function() {
var fName = document.getElementById("fname");
var fNameError = fName.nextElementSibling;
var lName = document.getElementById("lname");
var lNameError = lName.nextElementSibling;
if(fName.value.trim() === ""){
fNameError.innerHTML = "First Name Field Cannot Be Blank";
allowsubmit = false;
} else {
fNameError.innerHTML = "";
}
if(document.getElementById("lname").value.trim() === ""){
lNameError.innerHTML = "Last Name Field Cannot Be Blank";
allowsubmit = false;
} else {
lNameError.innerHTML = "";
}
var email = document.getElementById('email');
var emailError = email.nextElementSibling;
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
emailError.innerHTML = "Error in e-mail format";
return false;
} else {
emailError.innerHTML = "";
}
}
http://jsfiddle.net/Ty8AQ/10/
There are so many possiblities here, and so many examples on the web.
A possibility is creating an 'error-div' where you put all the error messages in. If you want you can style the div (color red etc etc)
HTML
<ul class="error-messages">
</ul>
JS
var li = document.createElement("li");
li.innerHTML = "Insert error message here";
document.querySelector("#ul.error-messages").appendChild(li);
CSS
.error-messages{color: red}
Another possibility are inline error messages next to the text box
Error messages when you hover on the input field
...

validation form : how to show error message all at one time for the blank input instead of one by one?

I want to validate my form, if any of the input field is blank, the error warning will show beside the blank input field. The error message must be comes out all at one time for the blank input, not show one by one. How to do this?
Below is my javascript code :
function doValidate()
{
var x=document.forms["form"]["fullname"].value;
if (x==null || x=="")
{
document.getElementById('error1').innerHTML="Full name is required!";
return false;
}
var y=document.forms["form"]["uid"].value;
if (y==null || y=="")
{
document.getElementById('error2').innerHTML="Username is required!";
return false;
}
var z=document.forms["form"]["pwd"].value;
if (z==null || z=="")
{
document.getElementById('error3').innerHTML="Password is required!";
return false;
}
var a=document.forms["form"]["pwd2"].value;
if (a==null || a=="")
{
document.getElementById('error4').innerHTML="Please re-enter your password!";
return false;
}
var pwd = document.getElementById("pwd").value;
var pwd2 = document.getElementById("pwd2").value;
if(pwd != pwd2){
alert('Wrong confirm password!');
return false;
}
var b=document.forms["form"]["role"].value;
if (b==null || b=="Please select...")
{
document.getElementById('error5').innerHTML="Please select user role!";
return false;
}
}
You should start your function with var ok = true, and in each if-block, instead of having return false, you should set ok = false. At the end, return ok.
Here's what that might look like:
function doValidate() {
var ok = true;
var form = document.forms.form;
var fullname = form.fullname.value;
if (fullname == null || fullname == "") {
document.getElementById('error1').innerHTML = "Full name is required!";
ok = false;
}
var uid = form.uid.value;
if (uid == null || uid == "") {
document.getElementById('error2').innerHTML = "Username is required!";
ok = false;
}
var pwd = form.pwd.value;
if (pwd == null || pwd == "") {
document.getElementById('error3').innerHTML = "Password is required!";
ok = false;
}
var pwd2 = form.pwd2.value;
if (pwd2 == null || pwd2 == "") {
document.getElementById('error4').innerHTML = "Please re-enter your password!";
ok = false;
} else if (pwd != pwd2) {
document.getElementById('error4').innerHTML = "Wrong confirm password!";
ok = false;
}
var role = form.role.value;
if (role == null || role == "Please select...") {
document.getElementById('error5').innerHTML = "Please select user role!";
ok = false;
}
return ok;
}
(I've taken the liberty of changing to a more consistent formatting style, improving some variable-names, simplifying some access patterns, and replacing an alert with an inline error message like the others.)

innerHTML is not hiding in javascript validation

function editvalidation() {
var isDataValid = true;
var currentCourseO = document.getElementById("currentCourseNo");
var newCourseNoO = document.getElementById("newCourseNo");
var currentCourseMsgO = document.getElementById("currentAlert");
var newCourseMsgO = document.getElementById("newAlert");
if (currentCourseO.value == "") {
currentCourseMsgO.innerHTML = "Please Select a Course to edit from the Course Drop Down Menu";
newCourseMsgO.innerHTML = "";
isDataValid = false;
} else {
currentCourseMsgO.innerHTML = "";
}
if (newCourseNoO.value == "") {
newCourseMsgO.innerHTML = "Please fill in the Course ID in your Edit";
isDataValid = false;
} else {
newCourseMsgO.innerHTML = "";
}
return isDataValid;
}
Hi, in the code above what I am trying to do is that if the currentCourseO.value == "" is met, then display its string message but do not display the string message for newCourseMsgO.
If currentCourseO.value == "" is not met then display the string for newCourseMsgO which is newCourseMsgO.innerHTML = "Please fill in the Course ID in your Edit"; if this validation is met.
At the moment it is not hiding the string for newCourseMsgO when currentCourseO.value == "" is met. Can I please have answer in javascript please.
It sounds like your two if-else statements should be connected, right now they are not dependent on one another. Try this:
if (currentCourseO.value == "") {
currentCourseMsgO.innerHTML = "Please Select a Course to edit from the Course Drop Down Menu";
newCourseMsgO.innerHTML = "";
isDataValid = false;
} else {
if (newCourseNoO.value == "") {
newCourseMsgO.innerHTML = "Please fill in the Course ID in your Edit";
isDataValid = false;
} else{
newCourseMsgO.innerHTML = "";
}
}

Categories