Javascript form validator function not working properly - javascript

I have been trying to make this function work for two hours now, but am not able to find where the error is.
This is behaving unexpectedly.
When any of the field in the form is filled, the form is posted to php file,
and shows errors (as expected) only when all fields are left empty, i.e.the 5 errors.
But when any of the 6 fields is filled, the form is posted irrespective of other errors in the form.
Please help me validating this form.
error is the information of errors I will show to users.
errors is number of errors found.
JavaScript function
function formValidator(){
var elementValue = document.getElementById("first-name").value;
var elementName = document.getElementById("first-name");
var errors = 0;
var error = " ";
if (elementValue == "" || elementValue == " " || elementValue== NULL){
error = "First Name shouldn't be left empty.";
errors = 1;
}
var elementValue = document.getElementById("last-name").value;
var elementName = document.getElementById("last-name");
if (elementValue == "" || elementValue == " " || elementValue== NULL){
if (errors == 0){
error = "Last Name shouldn't be left empty.";
}
else{
error += "<br>Last Name shouldn't be left empty.";
}
errors+=1;
}
var elementValue = document.getElementById("email-for-registration").value;
var elementName = document.getElementById("email-for-registration");
var email_err = "false";
if (elementValue == "" || elementValue == " " || elementValue== NULL){
email_err = "true";
}
var elementValue = document.getElementById("phone-for-registration").value;
if ((elementValue == "" || elementValue == " " || elementValue== NULL) && email_err == "true"){
if (errors == 0){
error = "Both email and contact cannot be left empty.";
}
else{
error += "<br>Both email and contact cannot be left empty.";
}
errors+=1;
}
var elementValue = document.getElementById("password-for-registration").value;
var elementName = document.getElementById("password-for-registration");
if (elementValue == "" || elementValue == " " || elementValue== NULL){
if (errors == 0){
error = "Password shouldn't be left empty.\nSelect a strong password atleast 6 characters long.";
}
else{
error += "<br>Password shouldn't be left empty.Select a strong password atleast 6 characters long.";
}
errors+=1;
}
else if (elementValue.length<6){
if (errors == 0){
error = "Password less than 6 characters aren't allowed for security reasons.";
}
else{
error += "<br>Password less than 6 characters aren't allowed for security reasons.";
}
errors+=1;
}
email_err = document.getElementById("confirm-password-for-registration").value;
var elementName = document.getElementById("confirm-password-for-registration");
if (elementValue != email_err){
if (errors == 0){
error = "The password to confirm doesn't match with your desired password.";
}
else{
error += "<br>The password to confirm doesn't match with your desired password.";
}
errors+=1;
}
var elementValue = document.getElementById("agreed-for-registration");
var elementName = document.getElementById("agreed-for-registration");
if (!elementValue.checked){
if (errors == 0){
error = "Please go through our <a href=''>Terms and Conditions</a>, and make sure you agree to continue.";
document.getElementById("agreed-for-registration").focus();
}
else{
error += "<br>Please go through our <a href=''>Terms and Conditions</a>, and make sure you agree to continue.";
}
errors+=1;
}
alert(errors);
if (errors > 1){
document.getElementById("form_errors").innerHTML = "<h4 style='color:red;'>Please remove the following errors from form to continue.</h4>";
document.getElementById("form_errors").innerHTML += "<h5>" + error + "</h5><br>";
return false;
} else if (errors == 1){
alert(error);
elementName.focus();
return false;
} else if (errors == 0){
return true;
}
return false;
}
Function called here.
<form name="registration" class="deco_blu_form" action="<?=$base_url;?>forms/confirm-registration/members.php" method="post" onsubmit="return formValidator();">
Please ask if any other information, code or explanation is required.

FIDDLE
You need to have elementValue === "NULL" or elementValue == null
I put console.log instead of alert and onblur trigger just for me to debug easier.
So the full code is:
function formValidator() {
var elementValue = document.getElementById("first-name").value;
var elementName = document.getElementById("first-name");
var errors = 0;
var error = " ";
if (elementValue == "" || elementValue == " " || elementValue === "NULL") {
error = "First Name shouldn't be left empty.";
errors = 1;
}
var elementValue = document.getElementById("last-name").value;
var elementName = document.getElementById("last-name");
if (elementValue == "" || elementValue == " " || elementValue === "NULL") {
if (errors == 0) {
error = "Last Name shouldn't be left empty.";
} else {
error += "<br>Last Name shouldn't be left empty.";
}
errors += 1;
}
var elementValue = document.getElementById("email-for-registration").value;
var elementName = document.getElementById("email-for-registration");
var email_err = "false";
if (elementValue == "" || elementValue == " " || elementValue === "NULL") {
email_err = "true";
}
var elementValue = document.getElementById("phone-for-registration").value;
if ((elementValue == "" || elementValue == " " || elementValue === "NULL") && email_err == "true") {
if (errors == 0) {
error = "Both email and contact cannot be left empty.";
} else {
error += "<br>Both email and contact cannot be left empty.";
}
errors += 1;
}
var elementValue = document.getElementById("password-for-registration").value;
var elementName = document.getElementById("password-for-registration");
if (elementValue == "" || elementValue == " " || elementValue === "NULL") {
if (errors == 0) {
error = "Password shouldn't be left empty.\nSelect a strong password atleast 6 characters long.";
} else {
error += "<br>Password shouldn't be left empty.Select a strong password atleast 6 characters long.";
}
errors += 1;
} else if (elementValue.length < 6) {
if (errors == 0) {
error = "Password less than 6 characters aren't allowed for security reasons.";
} else {
error += "<br>Password less than 6 characters aren't allowed for security reasons.";
}
errors += 1;
}
email_err = document.getElementById("confirm-password-for-registration").value;
var elementName = document.getElementById("confirm-password-for-registration");
if (elementValue != email_err) {
if (errors == 0) {
error = "The password to confirm doesn't match with your desired password.";
} else {
error += "<br>The password to confirm doesn't match with your desired password.";
}
errors += 1;
}
var elementValue = document.getElementById("agreed-for-registration");
var elementName = document.getElementById("agreed-for-registration");
if (!elementValue.checked) {
if (errors == 0) {
error = "Please go through our <a href=''>Terms and Conditions</a>, and make sure you agree to continue.";
document.getElementById("agreed-for-registration").focus();
} else {
error += "<br>Please go through our <a href=''>Terms and Conditions</a>, and make sure you agree to continue.";
}
errors += 1;
}
console.log(errors)
if (errors > 1) {
document.getElementById("form_errors").innerHTML = "<h4 style='color:red;'>Please remove the following errors from form to continue.</h4>";
document.getElementById("form_errors").innerHTML += "<h5>" + error + "</h5><br>";
return false;
} else if (errors == 1) {
alert(error);
elementName.focus();
return false;
} else if (errors == 0) {
return true;
}
return false;
}

At first, I count the following fields:
first-name
last-name
email-for-registration
phone-for-registration
password-for-registration
confirm-password-for-registration
agreed-for-registration
Just in case if you do something with the absolute value.
I have built a small prove-of-concept script and encountered that this script doesn't work, if you don't have an element with id #form_errors. Could this be your problem? This way the call for document.getElementById("form_errors") would result in undefined, and the function would not return false.
The same check for undefined elements holds of course for the other fields, too ;)

Related

Javascript For Loop Not Appending into Div as Expected?

Im not really sure what Im doing wrong here. I essentially check if any of the elements values are empty, and if they are it started to iterate through them.
Once it iterates it appends the id's of the elements that are empty into the div. Or at least thats what I expected it to do. Any help? Thanks!
<script>
function validate(){
var username = document.getElementById("username");
var name = document.getElementById("name");
var phone = document.getElementById("phone-number");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordc = document.getElementById("password-confirmation");
var array = [username, name, phone, email, password, passwordc];
if(username.value == "" || name.value == "" || phone.value == "" || email.value == "" || password.value == "" || passwordc.value == ""){
document.getElementById('required-field-error').innerHTML = "The following must not be blank: ";
for(i = 0; i < array.length; i++);{
if(array[i].value == ""){
document.getElementById('required-field-error').innerHTML += " array[i].id ";
}
else{document.getElementById('required-field-error').innerHTML += "";}
}
}
else{
document.getElementById('required-field-error').innerHTML = "";
}
}
</script>
You terminated the for loop independently and hence you are getting out of bond index. And also as pointer by 'Xufox' that is literal string.
Find the corrected script below:
<script>
function validate(){
var username = document.getElementById("username");
var name = document.getElementById("name");
var phone = document.getElementById("phone-number");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordc = document.getElementById("password-confirmation");
var array = [username, name, phone, email, password, passwordc];
if(username.value == "" || name.value == "" || phone.value == "" || email.value == "" || password.value == "" || passwordc.value == ""){
document.getElementById('required-field-error').innerHTML = "The following must not be blank: ";
for(i = 0; i < array.length; i++){
if(array[i].value == ""){
document.getElementById('required-field-error').innerHTML += " " + array[i].id;
}
else{document.getElementById('required-field-error').innerHTML += "";}
}
}
else{
document.getElementById('required-field-error').innerHTML = "";
}
}
</script>
You can greatly simplify your code by doing something like this instead:
function validate() {
const requiredFields = ['username', 'name', 'phone-number', 'email', 'password', 'password-confirmation'];
const missingFields = requiredFields.filter(requiredFieldStr => {
return !document.getElementById(requiredFieldStr).value;
});
const requiredFieldError = document.getElementById('required-field-error');
if (missingFields.length > 0) {
requiredFieldError.textContent =
"The following must not be blank: " + missingFields.join('');
} else requiredFieldError.textContent = '';
}
I don't know your requirement exactly.
But if you use JQuery validation that will simplify the things for you.

javascript validation not reading other conditions on my if else if

what could be wrong I tried to validate the input fields name, company_name, password, when I'm on the password field it says password should not be empty but I already inputted some characters on the password input field.
it doesn't seem to read the validation for password.length and password != confirm_password condition on my else if
here's my code
$('#button-parent a').bind('click',function(e){
var $this = $(this);
var prev = current;
var name = document.getElementById('name').value;
var company_name = document.getElementById('company_name').value;
var password = document.getElementById('password').value;
var confirm_password = document.getElementById('confirm_password').value;
var email = document.getElementById('email').value;
if( name == null || name == "") {
alert('name is required');
return false;
} else if( name.length < 5) {
alert('name must be atleast 6 characters');
return false;
} else if( company_name == null || company_name == ""){
alert('company name is required');
return false;
} else if ( password == null || password == ""){
alert('password field should not be empty');
return false;
} else if ( password.length < 8 ) {
alert('password must be atleast 8 characters');
return false;
} else if ( password != confirm_password ) {
alert('Password do not match');
return false;
}
rIf you are using jQuery why don't you get the values from $() selector?
$(function() {
$('#button-parent a').bind('click', function(e) {
var $this = $(this);
var prev = current;
var name = $('#name').val();
var company_name = $('#company_name').val();
var password = $('#password').val();
var confirm_password = $('#confirm_password').val();
var email = $('#email').val();
var errorMsg = '';
if (name == null || name == "") {
errorMsg += 'name is required\n';
}
if (name.length < 5) {
errorMsg += 'name must be atleast 6 characters\n';
}
if (company_name == null || company_name == "") {
errorMsg += 'company name is required\n';
}
if (password == null || password == "") {
errorMsg += 'password field should not be empty\n';
}
if (password.length < 8) {
errorMsg += 'password must be atleast 8 characters\n';
}
if (password != confirm_password) {
errorMsg += 'Password do not match';
}
if (errorMsg != '') {
alert(errorMsg);
return false;
}
});
});
This way you can show all the errors in the form at once and the users will not be irritated at all.
You can try to use the following line of code instead since you are using jQuery.
var password = $('#password').val();
For a quick check to see if this line works, you can type and run this command at the console section of the developer tool. If it works you should be seeing the input value.

I am having problems getting my form to validate or submit [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
My form does not seem to be validating or submitting. It was submitting and validating before, but the Jquery error messages were not all displaying at the same time so I had to edit the code, and now it is not submitting or validating at all.
Here is my JS:
function validateUserName(user)
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
return "You Left the Username field Emptyyy";
}
else if (uLength <4 || uLength > 11)
{
return "The Username must be between 4 and 11 characters";
}
else if (illegalChars.test(u))
{
return "The Username contains illegal charectors men!";
}
else
{
return "";
}
}
function validatePassword(pwd)
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
return "You left the password field empty";
}
else if (pLength < 6 || pLength > 20)
{
return "Your password must be between 6 and 20 characters in length";
}
else if (p != cP)
{
return "The passwords do not match!"
}
else
{
return "";
}
}
function validateEmail(email)
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (eLength == "" || eLength == null)
{
return "You left the email field blank!";
}
else if (e.match(illegalChars))
{
return "ILEGAL CHARECTORS DETECTED EXTERMINATE";
}
else
{
return "";
}
}
function validateFirstName(fname)
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if(fLength > 20)
{
return "First Name has a max of 20 characters";
}
else if (illegalChars.test(f))
{
return "Numbers,letter and underscores in first name only";
}
else
{
return "";
}
}
function validateLastName(lName)
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if(lLength > 100)
{
return "Last Name has a max of 100 characters";
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only";
}
else
{
return "";
}
}
function validateForm()
{
/*
valid = true;
//call username function
valid = valid && validateUserName();
//call password function
valid = valid && validatePassword();
//call email function
valid = valid && validateEmail();
//call first name function
valid = valid && validateFirstName();
//call first name function
valid = valid && validateLastName();
return valid;
*/
var error = "";
//call username function
error += "\n"+validateUserName();
//call password function
error += "\n"+validatePassword();
error += "\n"+validateEmail();
error += "\n" + validateFirstName();
error += "\n" + validateLastName();
if(error === ""){
return true;
}
else{
$("#ErrorUser").text(error);
$("#ErrorEmail").text(error);
$("#ErrorFname").text(error);
$("#ErrorPassword1").text(error);
$("#ErrorLname").text(error);
return false;
}
}
$('#your-form').submit(validateForm);
Fiddle: http://jsfiddle.net/cyKgD/
You had few errors in your code.
The validateForm() is never being called
Line 174: Should be else if (illegalChars.test(l))
Line 113: Closing bracket missing
This fiddle seems to be working now, http://jsfiddle.net/u5565/
Make sure that jQuery is included in your page. The line of code
$(function() {
$('#your-form').submit(function() {
return validateForm();
});
});
tells jQuery to validate the form when it is submitted.
In your fiddle, you forgot method="POST" on the form tag
<form name = "NewUser" id = "your-form" method="POST">

validate javascript expressions

I have done a test for a gender expression -
function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if(gender || gender1)
{
}
else
{
errorMsg = errorMsg + "please select your gender\n"
}
}
but I would like to be able to write it so that there is no need for an empty positive outcome like this -
if ((alphabetic.test(fname)== false) || (alphabetic.test(lname)== false))
{
alertmsg = alertmsg + "Name should be in alphabets:" + "\n";
}
I am sorry if I appear to be very stupid, I am a complete beginner. any help would be appreciated, thanks
function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if(!(gender || gender1))
{
errorMsg = errorMsg + "please select your gender\n"
}
}
If I understand correctly:
if(!gender && !gender1) {
errorMsg = errorMsg + "please select your gender\n"
}
Not really sure what you are trying to do but, try using the logical NOT "!":
function gender()
{
var gender = document.form1.radio[0].checked;
var gender1 = document.form1.radio[1].checked;
if !(gender || gender1)
{
errorMsg = errorMsg + "please select your gender\n"
}
}

Form submitting wrongfully

I am using a script to validate a few form fields before the form is submitted. The script is supposed to return false if the validations failed. On linux the script works fine in FF, Chrome and Opera. On windows the script fails and the forms is submitted on Chrome, Safari and IE.
Your thoughtswill be appreciated.
$(document).ready(function(){
// Place ID's of all required fields in the array.
required=["formname","formemail"];
email = $("#formemail");
name = $("#formname");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#suggestionform").submit( function(){
//validate required fields
for(i = 0; i < required.length; i++){
var input = $('#'+required[i]);
if( (input.val() == "") || (input.val() == emptyerror)){
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
}else {
input.removeClass("needsfilled");
}
}
if( !/^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())){
email.addClass("needsfilled");
email.val(emailerror);
}
if ( "" == name.val()){
name.addClass("needsfilled");
name.val(emptyerror);
}
if( $("#link1").val() + $("#link2").val() + $("#link3").val() + $("#link4").val() + $("#textarea1").val() + $("#textarea2").val() == "") {
errornotice.fadeIn(750);
alert("returning fail")
return false;
}
if( $(":input").hasClass("needsfilled")){
alert("returning fail here")
return false;
}else{errornotice.hide();return true;}
});
$(":input").focus( function(){
if ($(this).hasClass("needsfilled")){
$(this).val("");
$(this).removeClass("needsfilled");
}
})
});
Version 2
var required=["formname","formemail"];
var email = $("#formemail");
var name = $("#formname");
var errornotice = $("#error");
// The text to show up within a field when it is incorrect
var emptyerror = "Please fill out this field.";
var emailerror = "Please enter a valid e-mail.";
function suggestionSubmit(theform){
required=["formname","formemail"];
email = $("#formemail");
name = $("#formname");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
for(i = 0; i < required.length; i++){
var input = $('#'+required[i]);
if( (input.val() == "") || (input.val() == emptyerror)){
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
}else {
input.removeClass("needsfilled");
}
}
if( !/^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())){
email.addClass("needsfilled");
email.val(emailerror);
}
if ( "" == name.val()){
name.addClass("needsfilled");
name.val(emptyerror);
}
if( $("#link1").val() + $("#link2").val() + $("#link3").val() + $("#link4").val() + $("#textarea1").val() + $("#textarea2").val() == "") {
errornotice.fadeIn(750);
return false
}
if( $(":input").hasClass("needsfilled")){
return false;
}
else{errornotice.hide();return true;}
}
You can try to write smth like that
$(document).ready(function(){
// Place ID's of all required fields in the array.
required=["formname","formemail"];
email = $("#formemail");
name = $("#formname");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#suggestionform").submit( function(event){
//validate required fields
for(i = 0; i < required.length; i++){
var input = $('#'+required[i]);
if( (input.val() == "") || (input.val() == emptyerror)){
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
}else {
input.removeClass("needsfilled");
}
}
if( !/^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())){
email.addClass("needsfilled");
email.val(emailerror);
}
if ( "" == name.val()){
name.addClass("needsfilled");
name.val(emptyerror);
}
if( $("#link1").val() + $("#link2").val() + $("#link3").val() + $("#link4").val() + $("#textarea1").val() + $("#textarea2").val() == "") {
errornotice.fadeIn(750);
alert("returning fail")
event.preventDefault();
return false;
}
if( $(":input").hasClass("needsfilled")){
alert("returning fail here")
event.preventDefault();
return false;
}else{errornotice.hide();return true;}
});
Hope it helps.

Categories

Resources