I am trying to make a fail message which adds together different strings depending on the error on submit. However the fail message will not appear though the conditions are met.
I would like to know where is the error in my code. Thank you.
This is in an external JavaScript file which is linked to the HTML document.
function validationEvent() {
var flag = true;
var alertmsg = "There were errors found in your registration:";
var givenname = document.getElementById("gname").value;
var surname = document.getElementById("sname").value;
var address = document.getElementById("address1").value;
var city = document.getElementById("city").value;
var pcode = document.getElementById("pcode").value;
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var cnum = document.getElementById("cnum").value;
if (givenname == null || givenname == "") {
alertmsg += " Given Name is a mandatory field.";
flag = false;
}
if (surname == null || surname == "") {
alertmsg += " Surname is a mandatory field.";
flag = false;
}
if (address == null || address == "") {
alertmsg += " Address is a mandatory field.";
flag = false;
}
if (city == null || city == "") {
alertmsg += " City is a mandatory field.";
flag = false;
}
if (pcode == null || pcode == "") {
alertmsg += " Postal Code is a mandatory field.";
flag = false;
}
if (email == null || email == "") {
alertmsg += " Email is a mandatory field.";
flag = false;
}
if (phone == null || phone == "") {
alertmsg += " Phone Number is a mandatory field.";
flag = false;
}
if (cnum == null || cnum == "") {
alertmsg += " Credit Card Number is a mandatory field.";
flag = false;
}
if (!vormCredit()) {
alertmsg += " Visa Cards must start with 4 and Mastercard Cards must start with 5.";
flag = false;
}
if (!stateCheck()) {
alertmsg += " Invalid Postal Code.";
flag = false;
}
if (!checkCredit()) {
alertmsg += " Invaid Credit Card Number.";
flag = false;
}
if (!flag) {
alert(alertmsg);
return false;}
else {
alert("Thank you for your subcription.");
return true;}
};
Edit: Removed 'return false' from the 'if' loops and added it only to the if(!flag) loop.
It's better to use the switch statement here. It handles the situation when you have more cases. Also you can use break.
Related
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
I have been working on a script to check if fields are blank for my form. All of them work well, however for the birthday fields that utilise a select and option tag, when any month is chosen, the text "Choose a valid date" is still returned. I am trying to only output that text when a user chooses "Month" from the dropdown, and not let that return if a user chooses any normal month. Any help would be appreciated!
function validateStudentSignUpForm() {
var first = document.getElementById("first").value;
var last = document.getElementById("last").value;
var email1 = document.getElementById("email1").value;
var password1 = document.getElementById("password1").value;
var parentFirst = document.getElementById("parent-first").value;
var parentLast = document.getElementById("parent-last").value;
var childFirst = document.getElementById("child-first").value;
var email2 = document.getElementById("email2").value;
var password2 = document.getElementById("password2").value;
var month1 = document.getElementById("option-month1").value;
// First name can't be blank
if (first == "") {
document.getElementById("first").className = document.getElementById("first").className + " error";
document.getElementById("firstid").innerHTML = "Can't be blank";
}
// Last name can't be blank
if (last == "") {
document.getElementById("last").className = document.getElementById("last").className + " error";
document.getElementById("lastid").innerHTML = "Can't be blank";
}
// Email can't be blank
if (email1 == "") {
document.getElementById("email1").className = document.getElementById("email1").className + " error";
document.getElementById("email1id").innerHTML = "Can't be blank";
}
// Password can't be blank
if (password1 == "") {
document.getElementById("password1").className = document.getElementById("password1").className + " error";
document.getElementById("password1id").innerHTML = "Can't be blank";
}
// Parent first can't be blank
if (parentFirst == "") {
document.getElementById("parent-first").className = document.getElementById("parent-first").className + " error";
document.getElementById("parent-firstid").innerHTML = "Can't be blank";
}
// Parent last can't be blank
if (parentLast == "") {
document.getElementById("parent-last").className = document.getElementById("parent-last").className + " error";
document.getElementById("parent-lastid").innerHTML = "Can't be blank";
}
// Child first can't be blank
if (childFirst == "") {
document.getElementById("child-first").className = document.getElementById("child-first").className + " error";
document.getElementById("child-firstid").innerHTML = "Can't be blank";
}
// Email can't be blank
if (email2 == "") {
document.getElementById("email2").className = document.getElementById("email2").className + " error";
document.getElementById("email2id").innerHTML = "Can't be blank";
}
// Password can't be blank
if (password2 == "") {
document.getElementById("password2").className = document.getElementById("password2").className + " error";
document.getElementById("password2id").innerHTML = "Can't be blank";
}
// Month can't be default
if (month1 = "na") {
document.getElementById("option-month1").className = document.getElementById("option-month1").className + " error";
document.getElementById("date1id").innerHTML = "Choose a valid date";
}
return false;
}
There are two problems:
You're using the value of the option element, not the select. The value of the option element will always be "na". The value of the select will only be "na" if that option is the one that's selected.
You're using = instead of == in the comparison: if (month1 = "na") {. Since you only do that in that one comparison, I assume it's a typo, not a misunderstanding.
To fix it, put an id on the select and read its value, not the option's value, and use == in the comparison.
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;
}
}
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"];
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.)