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"];
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;
}
}
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.
I have a form myForm and I want to check if specific input field are filled out before sending the form. I'm very new to JavaScript so I don't really know what I did wrong. Any help is welcomed.
function validateForm() {
var validate = true;
var alert_string = "";
var children = $("#myForm").children("input");
console.log(children.size());
for(var i = 0; i < children.length ; i++){
if(children[i].attr(id).substring(0,8) != "ABC_FLAT"){
if(children[i].attr(id) == null || children[i].attr(id) == ""){
validate = false;
alert_string = alert_string.concat(childrern[i].attr(id)).concat(", ");
}
}
}
alert_string = alert_string.concat("must be filled out !");
if(validate == false){
alert(alert_string);
return false;
}
return true;
}
children[i].attr(id) == "" // wrong
You don't have to check whether their ids are null, you have to check whether their values are empty :)
if(children[i].value == "")
Since you are already using jQuery, you can simplify that code to a great extent. For example a simple "all fields filled" check can be
var flag=0;
$('#myForm').each(function() {
if ( $(this).val() === '' )
flag=1;
});
if you'll use jQuery, you can check the input fields if empty AND trap also white space/s. Add a class to all input fields , e.g. class="required" and add attribute fieldname with respective value for each input field.
var requiredFields = "";
$("#myForm").find('.required').each(function () {
if ($(this).val().trim().length == 0) {
requiredFields += " - " + $(this).attr("fieldname") + "\n";
}
});
if (requiredFields != "") {
alert("Please enter the following required field(s): \n" + requiredFields);
} else {
//save here
}
You can use required like <input required type="text" name="email" id="log" /> or use jQuery like
$("form").submit(function() {
var has_empty = false;
$(this).find('input').each(function() {
if(! $(this).val()) {
has_empty = true;
return false;
}
});
if(has_empty){return false;}
});