My form is not working well. Although there's error, it's still able to go through. Errflag is 1 but it goes to the '0'. Appreciate if someone can shed some light.
JSFiddle: https://jsfiddle.net/rezasan/xxqtuc7d/
HTML
<form id="contact_form">
<div class="medium-6 columns">
<input type="hidden" name="sourcepage" value="Index Page">
<input type="text" placeholder="NAME" name="name" id="name" required />
<input type="email" placeholder="EMAIL" name="email" id="email" required/>
<input type="text" placeholder="TEL" name="phone" id="phone" required/>
<select name="services" id="serviceslist">
<option value="services" selected>SERVICES</option>
<option value="botox">Botox</option>
<option value="filler">Filler</option>
<option value="Ultherapy">Ultherapy</option>
<option value="coolsculpting">CoolSculpting</option>
<option value="threadlift">Thread Lift</option>
<option value="others">Others</option>
</select>
<div class="errtext"></div>
</div>
<div class="medium-6 columns">
<textarea rows="6" cols="55" name="message" id="message" placeholder="Please enter your enquiries"></textarea>
<input type="submit" style="float:right;" id="submit" name="submit" class="formelement-submit">
</div>
</form>
JAVASCRIPT
function trimStr (str) {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
function checkTFieldValue(target,value,errorclass) {
if(trimStr($(target).val()) == value) {
$(target).addClass(errorclass);
return 1;
} else{
return 0;
}
}
function checkSFieldValue(target,value,errorclass) {
if(value == "SERVICES") {
$(target).addClass(errorclass);
return 1;
} else{
return 0;
}
}
function checkEmailValue(target,value,errorclass) {
var err = 0;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(trimStr($(target).val()) == value) {
$(target).addClass(errorclass);
err = 1;
} else if(!emailReg.test($(target).val())) {
$(target).addClass(errorclass);
err = 1;
}
return err;
}
$('#contact_form').append('<input type="hidden" name="jsauth" value="dryga-f"/>');
$('.formelement-submit').click(function(e){
e.preventDefault();
e.stopPropagation();
var errflag = 0;
var counter = 0;
$('.formerror').removeClass('formerror');
$('.errtext').empty();
var e = document.getElementById("serviceslist");
var strUser = e.options[e.selectedIndex].text;
errflag = checkTFieldValue('#name','','formerror');
errflag = checkEmailValue('#email','','formerror');
errflag = checkTFieldValue('#phone','','formerror');
errflag = checkSFieldValue('#serviceslist',strUser,'formerror');
errflag = checkTFieldValue('#message','','formerror');
if(errflag == 1){
$('.errtext').html('<p>*Please fill in all the required fields</p>');
}
if(errflag == 0){
$('.errtext').html('No error');
}
});
if #message is valid then it overwrites all others with 0.
you need to += the errflag and check for >:-
errflag += checkTFieldValue('#name','','formerror');
errflag += checkEmailValue('#email','','formerror');
errflag += checkTFieldValue('#phone','','formerror');
errflag += checkSFieldValue('#serviceslist',strUser,'formerror');
errflag += checkTFieldValue('#message','','formerror');
if(errflag > 0){
$('.errtext').html('<p>*Please fill in all the required fields</p>');
}
else {
$('.errtext').html('No error');
}
also, as #MarcoScabbiolo suggests, use submit instead of click.
When using forms, it's better to attach your validation handler into the form's submit event, not on the click of the submit button. Because there are other ways the form could submit, like pressing enter on an input.
Change
$('.formelement-submit').click(
To
$('#contact_form').on('submit',
It's working in this fiddler
Related
I have the following html and javascript code for validation on the input fields, this was working with the one input field for first name but since I tried to extend my code by adding a new input field for last name now the form validation has stopped working as follows:
function myFunction() {
let x = document.getElementsByName("first_name").[0]value;
let y = document.getElementsByName("last_name")[0].value;
let text;
text = "";
if (x == '' || x == null) {
text = "Input not valid";
}
document.getElementById("first_name_errors").innerHTML = text;
}
if (y == '' || y == null) {
text = "Input not valid";
}
document.getElementById("last_name_errors").innerHTML = text;
}
document.addEventListener('invalid', (function () {
return function (e) {
e.preventDefault();
document.getElementsByName("first_name").focus();
document.getElementsByName("last_name").focus();
};
})(), true);
</head>
<body>
<input type="text" name="first_name" placeholder="first name" name class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="myFunction()">
<br><br>
<input type="text" name="last_name" placeholder="last name" name class="input_fields" required>
<div class="error-message" id="last_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_lname" onclick="myFunction()">
How can I get this back working with the extra input field last name added? Thanks in advance
there are many errors here. you may find them by your own by debugging your console.log
error, at let x = document.getElementsByName("first_name").[0]value;
there are a to many }
eventlisteners need to be on the input and shouldn't be inside the check function
there are empty name attributes on your inputs
fixing it blind it would be something like:
let firstName = document.getElementsByName('first_name')[0];
let lastName = document.getElementsByName('last_name')[0];
function checkValid() {
let x = firstName.value;
let y = lastName.value;
let text;
text = '';
if (x == '' || x == null) {
text = 'Input not valid';
}
document.getElementById('first_name_errors').innerHTML = text;
if (y == '' || y == null) {
text = 'Input not valid';
}
document.getElementById('last_name_errors').innerHTML = text;
}
firstName.addEventListener('invalid', function () {
firstName.focus();
});
lastName.addEventListener('invalid', function () {
lastName.focus();
});
<input type="text" name="first_name" placeholder="first name" class="input_fields" required>
<div class="error-message" id="first_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_fname" onclick="checkValid()">
<br><br>
<input type="text" name="last_name" placeholder="last name" class="input_fields" required>
<div class="error-message" id="last_name_errors"></div>
<input class="save_btn" type="submit" value="Save" name="save_lname" onclick="checkValid()">
I have a problem, I made a form validation in javascript and after all validation checks I put innerHtml += "actually error message" and the problem is how many times I click the submit button it writes out the message. Someone can help me to solve this? Or make this more elegant or better logic. I'm a beginner.
function regvalidate() {
var errortable = document.getElementById('log');
var x = document.forms["regform"]["username"].value;
var y = document.forms["regform"]["email"].value;
var z = document.forms["regform"]["pass1"].value;
var b = document.forms["regform"]["pass2"].value;
if (x == "" || y == "" || z == "" || b == "") {
errortable.innerHTML = 'Cant be empty field';
return false;
}
var regexEmail = /\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/;
var email = document.getElementById("email");
if (regexEmail.test(email.value)) {} else {
errortable.innerHTML += 'Invaild email address';
return false;
}
password1 = regform.pass1.value;
password2 = regform.pass2.value;
if (password1 != password2) {
errortable.innerHTML += 'Two pass dosent match';
return false;
}
}
<div id="log"></div>
<form id="regform" class="form-signin" action="#" method="post">
<input type="text" id="username" class="form-control" placeholder="username" name="username">
<input type="email" id="email" class="form-control" placeholder="email" name="email">
<input type="password" id="pass1" class="form-control" placeholder="password" name="password_1">
<input type="password" id="pass2" class="form-control" placeholder="password again" name="password_2">
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" onClick="return regvalidate()" name="register_btn">Register</button>
</form>
just remove the + before =like the following
errortable.innerHTML += 'Two pass dosent match';
or do it like
errortable.innerHTML = '';
errortable.innerHTML += 'Two pass dosent match';
I've tried this many different ways... don't know why this is redirecting still. I suppose in the past I've always used a button instead of a submit input and as such I never ran into this issue. However, I think it's time to get to the bottom of this!
HTML FORM
<form class="col-xs-12" action="mail.php" method="POST" >
<h2 class="headerFont">Contact</h2>
<p>Use the form below to send to contact me via email. I will be in touch soon after receiving your message.</p>
<div class="row">
<div class="col-xs-12 col-sm-6">
<input class="col-xs-12" placeholder="Full Name" title="Enter Full Name" type="text" name="name">
<input class="col-xs-6" placeholder="Email Address" title="Enter Email Address" type="email" name="email">
<input class="col-xs-6" placeholder="Mobile Phone Number" title="Enter Mobile Phone Number" type="tel" name="phone">
<input class="col-xs-12" placeholder="Street Address" title="Enter Street Address" type="text" name="address">
<input type="text" name="_gotcha" id="_gotcha" style="display: none !important">
<select class="col-xs-12" name="service">
<option selected disabled>Select Service</option>
<option>Group Walking</option>
<option>Private Walking</option>
<option>Pet Sitting</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<textarea class="col-xs-12" placeholder="Message Here" rows="10" name="message"></textarea>
</div>
</div>
<input type="submit" value="Send" onclick="formSubmit(e)">
</form>
JAVASCRIPT CODE
function formSubmit(e) {
e.preventDefault();
return false;
console.log("Ajax Init");
var form = e.target,
data = new FormData(),
xhr = new XMLHttpRequest();
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
data.append(input.name, input.value);
if (input.getAttribute("name") !== "_gotcha") {
if (input.value === "" || input.value === null || input.value === "undefined") {
alert("Please fill out all form fields before submitting");
break;
}
}
}
xhr.open(form.method.toUpperCase(), form.action, true);
if (document.getElementById("_gotcha").value.length == 0){
xhr.send(data);
} else {
break;
}
xhr.onloadend = function () {
// done
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
input.value = "";
}
alert("Message Sent - Thank You");
};
};
It seems a better option is to use onsubmit attribute.
function formSubmit(form) {
console.log("Ajax Init");
var data = new FormData(form), // simpler
xhr = new XMLHttpRequest();
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
//data.append(input.name, input.value);
if (input.getAttribute("name") !== "_gotcha") {
if (input.value === "" || input.value === null || input.value === "undefined") {
alert("Please fill out all form fields before submitting");
// something went wrong, prevent form from submitting
return false;
}
}
}
xhr.open(form.method.toUpperCase(), form.action, true);
if (document.getElementById("_gotcha").value.length == 0) {
xhr.send(data);
} else {
// something went wrong, prevent form from submitting
return false;
}
xhr.onloadend = function() {
// done
for (var i = 0, ii = form.length - 1; i < ii; ++i) {
var input = form[i];
input.value = "";
}
alert("Message Sent - Thank You");
};
// everything went ok, submit form
return true;
};
<!-- note the use of return -->
<form class="col-xs-12" action="mail.php" method="POST" onsubmit="return formSubmit(this)">
<h2 class="headerFont">Contact</h2>
<p>Use the form below to send to contact me via email. I will be in touch soon after receiving your message.</p>
<div class="row">
<div class="col-xs-12 col-sm-6">
<input class="col-xs-12" placeholder="Full Name" title="Enter Full Name" type="text" name="name">
<input class="col-xs-6" placeholder="Email Address" title="Enter Email Address" type="email" name="email">
<input class="col-xs-6" placeholder="Mobile Phone Number" title="Enter Mobile Phone Number" type="tel" name="phone">
<input class="col-xs-12" placeholder="Street Address" title="Enter Street Address" type="text" name="address">
<input type="text" name="_gotcha" id="_gotcha" style="display: none !important">
<select class="col-xs-12" name="service">
<option selected disabled>Select Service</option>
<option>Group Walking</option>
<option>Private Walking</option>
<option>Pet Sitting</option>
</select>
</div>
<div class="col-xs-12 col-sm-6">
<textarea class="col-xs-12" placeholder="Message Here" rows="10" name="message"></textarea>
</div>
</div>
<!-- upon clicking on the submit button, it will trigger the form's onsubmit handler -->
<input type="submit" value="Send">
</form>
i suggest to use jquery inside of core javascript becuase in javascript it to mush code want to write , i write for you in jquery
step 1: : give id to form tag id="myForm"
step 2: : write script like this
<script>
$('#myForm').submit(function(e){
e.preventDefualt();
data = $(this)..serialize();
});
</script>
This is my first real project which involves form validation. I am experiancing a problem which I can not find the solution to.
The objective is this, there is a continue button which will be activated once all the field inputs have been passed as valid. I am going about this by creating seperate variables, all initially set as false, devoted to checking each input field. When the user has entered correct validation data, the variable is set to true.
I then run an if statement to check if all the variables are set to true, and if so, I activate the continue button which, when clicked, slides the next part of the form into the page.
HTML:
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" id="submit" value="CONTINUE">
</div>
</div>
</div>
JAVASCRIPT / JQUERY:
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input",function(){
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility","visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)){
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility","visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility","hidden");
emailValidated = true;
}
})
//name validation check//
nameField.on("input",function(){
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility","visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility","hidden");
nameValidated = true;
}
})
//contact number validation check//
numberField.on("input",function(){
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility","visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility","hidden");
numberValidated = true;
}
})
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
})
at the moment, I am simply using the alert prompt to test if it is working, but it fails.
As mentioned, this is my first real form validation. Any other tips or advice would be greatly appreciated. Thanks for the help in advance.
There were a couple things that I found from copying pasting your snippets of code. 1 there was an ending "})" without a beginning $(document).ready(function(){ ". 2 none of your ".on" statements had an ending semi colon.
Here is my javascript with a small change
$(document).ready(function () {
//collection of input form fields//
var formSubmit = $("#submit");
var emailField = $("#email");
var nameField = $("#name");
var numberField = $("#number");
//Switch to true when each validation has passed//
emailValidated = false;
nameValidated = false;
numberValidated = false;
//email validation check//
emailField.on("input", function () {
var emailInput = $(this).val()
var testExp = new RegExp(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$/);
if (emailInput < 1) {
$("#email-warning").html("Email is required!");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
}
else if (!testExp.test(emailInput)) {
$("#email-warning").html("Please enter a valid email");
$("#email-warning").css("visibility", "visible");
emailValidated = false;
} else {
$("#email-warning").css("visibility", "hidden");
emailValidated = true;
enableContinue();
}
});
//name validation check//
nameField.on("input", function () {
var nameInput = $(this).val()
if (nameInput < 1) {
$("#name-warning").html("Name is required");
$("#name-warning").css("visibility", "visible");
nameValidated = false;
} else {
$("#name-warning").css("visibility", "hidden");
nameValidated = true;
enableContinue();
}
});
//contact number validation check//
numberField.on("input", function () {
var numberInput = $(this).val()
if (typeof numberInput !== "number" && numberInput.length < 9) {
$("#number-warning").html("Please enter a valid number");
$("#number-warning").css("visibility", "visible");
numberValidated = false;
} else {
$("#number-warning").css("visibility", "hidden");
numberValidated = true;
enableContinue();
}
});
enableContinue = function () {
if (emailValidated && nameValidated && numberValidated) {
$('#submit').prop('disabled', false);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h3>Step 3: Your Details</h3>
<!-- SLIDE-IN DIV TO REPRESENT DAY PASS -->
<div class="row chosenmembership">
<div class="col-md-12 text-center" id="yourdetails">
<form action="" method="">
<div class="form-group">
<label for="email">Email:</label>
<input type="text" placeholder="Email Address" id="email" class="form-control your-details">
<span class="warning" id="email-warning"></span>
</div>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" placeholder="Full Name" id="name" class="form-control your-details">
<span class="warning" id="name-warning"></span>
</div>
<div class="form-group">
<label for="number">Contact Number:</label>
<input type="text" placeholder="Contact Number" id="number" class="form-control your-details">
<span class="warning" id="number-warning"></span>
</div>
<div class="form-group">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" class="form-control your-details">
<span class="warning" id="dob-warning"></span>
</div>
</form>
<input type="submit" class="btn btn-primary" id="submit" disabled="disabled" value="CONTINUE">
</div>
</div>
</div>
Your form CONTINUE button becomes enables once all fields have a value. Note: I did not try to improve your javascript any, just made it work.
Right now you synchronically check validation variables at script, so they are all false. You have to asynchronically check them after form submit. Just add event listener to form submit to check variables like this:
document.getElementById('#form').addEventListener('submit', function(){
if (emailValidated && nameValidated && numberValidated){
alert("correct");
}
});
Don't forget to set id to your form.
You may be able to save a lot of work if you leverage some of the built in HTML5 form validation. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
This simple example adds a new field every time you submit the form, as long as the existing fields are valid. You would need to test the state of the form to see if you should be adding another section or submitting.
$('form').on('submit', function() {
$(this).find('fieldset').append('<input type="text" required />');
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<input type="text" required />
</fieldset>
<input type="submit" id="submit" value="continue" />
</form>
Hello I trying to validate my form using onsubmit attribute. But it does not work. And the funniest thing in this story - this works properly only 2 days ago.
Form tag :
<form action="../actionHandlers/registrationHandler.php" onsubmit="return validateRegistrationForm()" method="post" name="reg_form" enctype="multipart/form-data" id="reg_form">
Validate function:
function validateRegistrationForm() {
var errors = [];
if (document.forms['reg_form']['username'].value.length == 0) {
var usernameErrorMessage = localStorage.getItem('emptyLoginError');
errors.push(usernameErrorMessage);
}
if (document.forms['reg_form']['password'].value.length == 0) {
var passwordErrorMessage = localStorage.getItem('emptyPasswordError');
errors.push(passwordErrorMessage);
}
if (!validateEmail(document.forms['reg_form']['email'].value)) {
var emailErrorMessage = localStorage.getItem('emailInvalidError');
errors.push(emailErrorMessage);
}
if (errors.length > 0) {
var htmlErrors = '';
for (var i = 0; i < errors.length; i++) {
htmlErrors += errors[i] + "<br />";
}
document.getElementById("error_message").innerHTML = htmlErrors;
return false;
} else {
return true;
}
}
Where is my mistake? Please help)
Validate email:
function validateEmail(email) {
var pattern = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
return pattern.test(email);
}
Inputs:
<div>
<label for="username" id="username_label"><?php echo $languageArray['USERNAME'] ?></label><span id="required_mark">*</span><br/>
<input type="text" name="username" id="username_field" class="input_form_fields">
</div>
<div>
<label for="password"><?php echo $languageArray['PASSWORD'] ?></label><span id="required_mark">*</span><br/>
<input type="password" name="password" id="password_field" class="input_form_fields">
</div>
<div>
<label for="email"><?php echo $languageArray['EMAIL'] ?></label><span id="required_mark">*</span><br/>
<input type="text" name="email" id="email_field" class="input_form_fields">
</div>
Try this code, I have tested it and its working:
<form action="../actionHandlers/registrationHandler.php" onsubmit="return validateRegistrationForm()" method="post" name="reg_form" enctype="multipart/form-data" id="reg_form">
<div>
<label for="username" id="username_label"><?php echo (isset($languageArray['USERNAME']) ? $languageArray['USERNAME'] : "email"); ?></label><span id="required_mark">*</span><br/>
<input type="text" name="username" id="username_field" class="input_form_fields">
</div>
<div>
<label for="password"><?php echo (isset($languageArray['PASSWORD']) ? $languageArray['PASSWORD'] : "email"); ?></label><span id="required_mark">*</span><br/>
<input type="password" name="password" id="password_field" class="input_form_fields">
</div>
<div>
<label for="email"><?php echo (isset($languageArray['EMAIL']) ? $languageArray['EMAIL'] : "email"); ?></label><span id="required_mark">*</span><br/>
<input type="text" name="email" id="email_field" class="input_form_fields">
</div>
<input type="submit">
</form>
And the JS:
function validateEmail(email) {
var pattern = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
return pattern.test(email);
}
function validateRegistrationForm(e) {
var errors = [];
if (document.forms['reg_form']['username'].value.length == 0) {
var usernameErrorMessage = localStorage.getItem('emptyLoginError') ? localStorage.getItem('emptyLoginError') : "username error";
errors.push(usernameErrorMessage);
}
if (document.forms['reg_form']['password'].value.length == 0) {
var passwordErrorMessage = localStorage.getItem('emptyPasswordError') ? localStorage.getItem('emptyPasswordError') : "password error";
errors.push(passwordErrorMessage);
}
if (!validateEmail(document.forms['reg_form']['email'].value)) {
var emailErrorMessage = localStorage.getItem('emailInvalidError') ? localStorage.getItem('emailInvalidError') : "email error";
errors.push(emailErrorMessage);
}
if (errors.length > 0) {
var htmlErrors = '';
for (var i = 0; i < errors.length; i++) {
htmlErrors += errors[i] + "<br />";
}
if(document.getElementById("error_message")){
document.getElementById("error_message").innerHTML = htmlErrors;
}
return false;
} else {
return true;
}
}
The way I see it the problem were caused by any of the following:
localStorage.getItem notice that you don't even check to see if the key exists.
echo $languageArray['PASSWORD'] again there is no check at all, although I'm sure its not php error but its good to check before you echo.
document.getElementById("error_message"), well you use the innerHTML but the document.getElementById my return undefined.
Conclusion:
The code should work.
But:
You say it worked before, I'm thinking you have touched the html in one way or another, if its not the html check the localStorage keys.