I have created functions to validate my form. But I want them all to run at once when I click the submit button. So, I have a formValidate function, and then I have a firstNameValidate, lastNameValidate ect.
My question is, how would I create the formValidate function to run the functions i have, but ONLY submit the form if all of them are true?
function firstNameValidate() {
// Making sure that the firstname input is not blank
if (firstName.value.length == 0) {
// If the firstname input is blank, then return the error text below
error.innerHTML = 'Please Enter a Valid First Name, Cannot be Blank';
// Error text css class
error.className = 'error';
// Making sure that the browser window focuses on the error
firstName.focus();
// Does not let the browser submit the form
// this statement makes sure that the input has only letters
return false;
} else if (!firstName.value.match(letter)) {
// // If the input has something other then numbers, show this error.
error.innerHTML =
'Please Enter a Valid First Name, Cannot contain characters(!##) or numbers';
// // error text css class
error.className = 'error';
// browser window focuses on error
firstName.focus();
// Form does not submit
return false;
}
if (firstName.value.length > 0 && firstName.value.match(letter)) {
error.className = '';
error.innerHTML = '';
return true;
}
}
I can get the first name and last name to validate, however if one them is filled out it sends the form. So the return true and return false I think are wrong.
function firstNameValidate() {
if (firstName.value.length == 0) {
error.innerHTML = 'Please Enter a Valid First Name, Cannot be Blank';
error.className = 'error';
firstName.focus();
return false;
}
if (!firstName.value.match(letter)) {
error.innerHTML = 'Please Enter a Valid First Name, Cannot contain characters(!##) or numbers';
error.className = 'error';
firstName.focus();
return false;
} else {
//intended code goes here , or simply return true.
}
}
If you want to do strict checking then write all the validation in if statement, and if everything is filled properly then do the correct code in an else statement,
and call the above function on form onsubmit or on a button click it will do the work..
Hope this helps ..!!
Related
Onclick and jQuery click working together but return false not working in jquery. I want to validate fields before on onclick open next page. Problem with my code is that if filed are blank in that case it open next page. I use return false in each empty case. So until all fields are not filled up. next page should not open.
Html Code
<button id="onepage-guest-register-button" type="button" class="button secondary" onclick="$('login:guest').checked=true; checkout.setMethod();"><span><span><?php //echo $this->__('Checkout as Guest') ?></span></span></button>
jQuery Code
jQuery('#onepage-guest-register-button').click(function(e){
var email=jQuery('#login-email').val();
jQuery('.validate-email').attr('value', email);
var login_name = jQuery('#login_name').val();
var login_phone = jQuery('#login_phone').val();
var login_email = jQuery('#login_email').val();
alert("name"+login_name+'phone'+login_phone+'email'+login_email);
if(login_name==''){ jQuery('.login_name').text('Please enter full name'); return false; }else{ jQuery('.login_name').empty();}
if(login_phone==''){ jQuery('.login_phone').text('Please enter Phone Number');return false;}else{ jQuery('.login_phone').empty();}
if(login_email==''){ jQuery('.login_email').text('Please enter Phone email');return false;}else{ jQuery('.login_email').empty();}
//alert('trigger');
jQuery('#onepage-guest-register-button').trigger('onclick');
});
Don't mix onclick attribute with onclick event handler. It's just plain silly.
In most cases, it's better to go with the latter.
1) Remove onclick attribute
<button id="onepage-guest-register-button" type="button" class="button secondary"><span><span><?php echo $this->__('Continue') ?></span></span></button>
2) Move the logic into your onclick event handler.
jQuery('#onepage-guest-register-button').click(function(e){
// no idea
var email = jQuery('#login-email').val();
jQuery('.validate-email').attr('value', email);
// get values
var login_name = jQuery('#login_name').val();
var login_phone = jQuery('#login_phone').val();
var login_email = jQuery('#login_email').val();
// flag if errors is found; assume no errors by default
var err = false;
// clear errors?
jQuery('.login_name').empty();
jQuery('.login_phone').empty();
jQuery('.login_email').empty();
// show errors if any
if (login_name == '') {
jQuery('.login_name').text('Please enter full name');
err = true;
}
if (login_phone == ''){
jQuery('.login_phone').text('Please enter Phone Number');
err = true;
}
if (login_email == ''){
jQuery('.login_email').text('Please enter Phone email');
err = true;
}
// do the appropriate action depending if there are errors or not
if (err) {
return false;
} else {
$('login:guest').prop('checked', true);
checkout.setMethod();
}
});
The following code loops when the page loads and I can't figure out why it is doing so. Is the issue with the onfocus?
alert("JS is working");
function validateFirstName() {
alert("validateFirstName was called");
var x = document.forms["info"]["fname"].value;
if (x == "") {
alert("First name must be filled out");
//return false;
}
}
function validateLastName()
{
alert("validateLastName was called");
var y = document.forms["info"]["lname"].value;
if (y == "") {
alert("Last name must be filled out");
//return false;
}
}
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
fn.onfocus = validateFirstName();
alert("in between");
ln.onfocus = validateLastName();
There were several issues with the approach you were taking to accomplish this, but the "looping" behavior you were experiencing is because you are using a combination of alert and onFocus. When you are focused on an input field and an alert is triggered, when you dismiss the alert, the browser will (by default) re-focus the element that previously had focus. So in your case, you would focus, get an alert, it would re-focus automatically, so it would re-trigger the alert, etc. Over and over.
A better way to do this is using the input event. That way, the user will not get prompted with an error message before they even have a chance to fill out the field. They will only be prompted if they clear out a value in a field, or if you call the validateRequiredField function sometime later in the code (on the form submission, for example).
I also changed around your validation function so you don't have to create a validation function for every single input on your form that does the exact same thing except spit out a slightly different message. You should also abstract the functionality that defines what to do on each error outside of the validation function - this is for testability and reusability purposes.
Let me know if you have any questions.
function validateRequiredField(fieldLabel, value) {
var errors = "";
if (value === "") {
//alert(fieldLabel + " must be filled out");
errors += fieldLabel + " must be filled out\n";
}
return errors;
}
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
fn.addEventListener("input", function (event) {
var val = event.target.value;
var errors = validateRequiredField("First Name", val);
if (errors !== "") {
alert(errors);
}
else {
// proceed
}
});
ln.addEventListener("input", function (event) {
var val = event.target.value;
var errors = validateRequiredField("Last Name", val);
if (errors !== "") {
alert(errors);
}
else {
// proceed
}
});
<form name="myForm">
<label>First Name: <input id="fn" /></label><br/><br/>
<label>Last Name: <input id="ln"/></label>
</form>
Not tested but you can try this
fn.addEventListener('focus', validateFirstName);
ln.addEventListener('focus', validateLastName);
I have the following form, done with HTML and Javascript validation.
var submitOK=true;
function validate(){
submitOK=true;
checkName();
checkSurname();
checkCourse();
checkDate();
checkEmail();
if(submitOK == false) {
return false;}
}
function checkName() {
var name = document.getElementById("name");
if(myform.name.value.length==0)
{
document.getElementById("checkname").innerHTML="Please, enter a valid name";
submitOK=false;
}
}
(COMPLETE CODE IN HERE)
http://jsfiddle.net/unkok6or/
The fields Course, Date, Name, Surname and Email have to be required. I don't know why my code is wrong and how to fix it.
-What I would like, is an error message to appear if one of the fields is not complete. Now the form runs and works even if one of them is not completed.
-The email with the correct format (without Regex).
Thanks in advance! :)
I simplified your code a little bit. This worked for me. The key thing to remember that your submit function must return a true to submit or false to stop the submit.
var submitOK=true;
function validate(){
submitOK=true;
checkName();
checkSurname();
checkCourse();
checkDate();
checkEmail();
return submitOK;
}
function checkName() {
if( document.getElementById("name").value.length==0)
{
document.getElementById("checkname").innerHTML="Please, enter a valid name";
submitOK=false;
}
}
function checkSurname() {
if(document.getElementById("surname").value.length==0)
{
document.getElementById("checksurname").innerHTML="Please, enter a valid surname";
submitOK=false;
}
}
function checkEmail() {
if(document.getElementById("email").value.length==0)
{
document.getElementById("checkemail").innerHTML="Please, enter an email";
submitOK=false;
}
}
function checkCourse() {
if(document.getElementById("course").selectedIndex < 1 ) {
document.getElementById("checkcourse").innerHTML="Please, select a course";
submitOK=false;
}
}
function checkDate() {
if(document.getElementById("date").selectedIndex < 1) {
document.getElementById("checkdate").innerHTML="Please, select a date";
submitOK=false;
}
}
You need to return true when your validation passes so change
if(submitOK == false) {
return false;}
to
return submitOk;
If you just need to make sure all the fields are filled, why don't you use required keyword on ur input types.
And for drop down you can disable the select option that way you don't need to check if the user has selected the default value.
I'm trying to validate a form that will send an email. At the moment the button returns formCheck() onclick. Which is meant to display a popup respective of field completetion.
I'm new to JS so I'm having a little trouble working out what I'm doing wrong as the outcome is always the else "Thanks".
<script>
function formCheck() {
if (document.getElementById("Name") === "")
{
alert("please enter name");
}
else if (document.getElementById("Email") === "")
{
alert("Please enter an email address");
}
else if (document.getElementById("Name") && document.getElementById("Email") === "")
{
alert("Please enter a Name and Email address");
}
else {
alert("Thanks");
}
}
</script>
To me it looks like I'm either not using an if statementcorrectly or its not picking up the fields are empty when defined as "". If anybody can point me in the right direction it would be much appreciated.
You should be comparing the value instead of the object itself:
document.getElementById("Name").value
I am trying to remake a jQuery script by (http://jorenrapini.com/blog/javascript/the-simple-quick-and-small-jquery-html-form-validation-solution). This script is checking if a from is filled, if not a error message will appear.
What I want to do is to only get the error message when one of two form input-fields are filled out, if none of them are then they should be ignored. The form fields are named "firstinput" and "secondinput" (you can see their id in the code).
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstinput", "secondinput"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
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.";
$("#theform").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");
}
}
// Validate the e-mail.
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 any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
Can anybody please help me with a solution, I would really appreciate it.
/A girl that spend a LOT of time solving this without luck :(
I would wrap your for loop in a conditional that evaluates if one or the other has a value.
if($("#field1").val() == "" && $("#field2").val() == ""){
//Ignore
}else{
//Do something
}
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstinput", "secondinput"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
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.";
$("#theform").submit(function(){
//Validate required fields
if($("#firstinput").val() != "" || $("#secondinput").val() != "")
{
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");
}
}
}
// Validate the e-mail.
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 any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});