Form Validation w/Javascript - Not working - javascript

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.

Related

Javascript form validation code looping

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);

Javascript else if statement not working with form validation

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

How do I use javascript to prevent form submission because of empty fields?

How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.
HTML Code :-
<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>
Javascript Code :-
function runMyFunction()
{
if (document.getElementsByName("name")[0].value == "")
{
alert("Please enter value");
}
else
{
var form= document.getElementsByName("form")[0];
form.submit();
}
}
Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.
If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName
function checkForm(form1)
{
if (form1.elements['FieldName'].value == "")
{
alert("You didn't fill out FieldName - please do so before submitting");
return false;
}
else
{
form1.submit();
return false;
}
}
This is untested code but it demonstrates my method.
It will check any text field in 'form' for empty values, and cancel the submit action if there are any.
Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.
window.onload = function (event) {
var form = document.getElementsByName('form')[0];
form.addEventListener('submit', function (event) {
var inputs = form.getElementsByTagName('input'), input, i;
for (i = 0; i < inputs.length; i += 1) {
input = inputs[i];
if (input.type === 'text' && input.value.trim() === '') {
event.preventDefault();
alert('You have empty fields remaining.');
return false;
}
}
}, false);
};
Attach an event handler to the submit event, check if a value is set (DEMO).
var form = document.getElementById('test');
if (!form.addEventListener) {
form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
form.addEventListener("submit", checkForm, false);
}
function checkForm(e) {
if(form.elements['name'].value == "") {
e.preventDefault();
alert("Invalid name!");
}
}

JQuery Validation for Two Password Fields

Two entered passwords should be the same, and I want to display a notification when they're not matching. The target is to display the notification during typing and not after pressing the save Button.
I am new to javascript and I have also tried the functionname function() notation.
following js:
function updateError (error) {
if (error == true) {
$(".error").hide(500);
}else{
$(".error").show(500);
}
};
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return true;
}
return false;
};
document.ready(function(){
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
});
and HTML:
#Html.Password("password")
#Html.Password("password-check")
<span class="error">Errortext</span> </td></tr>
but it doesn't works..
Thx!
Edit:
Now i've changed the JS code to:
$("input[name=password-check]").keyup(function(){updateError(checkSame());});
$("input[name=password]").keyup(function(){updateError(checkSame());});
--> now it works, but only once, after the user typed a matching password, validation stops working
Solved, problem was Quoting:
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
You are doing opposite
if (error == true) {
    $(".error").show(500);
}else{
 $(".error").hide(500);
}
Edit as per comment :
Try placing name within quotes like
$("input[name='password-check']").keyup(function(){updateError(checkSame());});
$("input[name='password']").keyup(function(){updateError(checkSame());});
In the checkSame, you may want to use indexOf to check if passwordVal contains checkVal since when typing, the password is not equal yet.
if (passwordVal.indexOf(checkVal)>-1 || checkVal.indexOf(passwordVal)>-1 ) {
return true;
}
As int2000 said, fire the checkSame on keyup seems weird, but if it's what you want, OK.
Try to change your checkSame function as follows:
function checkSame() {
var passwordVal = $("input[name=password-check]").val();
var checkVal = $("input[name=password]").val();
if (passwordVal == checkVal) {
return false;
}
return true;
};
Remember that you're passing the result of checkSame to updateError, so if the passwords are the same you have no error.

How to check for empty values on two fields then prompt user of error using javascript

I hope I can explain this right I have two input fields that require a price to be entered into them in order for donation to go through and submit.
The problem that I am having is that I would like the validation process check to see if one of the two fields has a value if so then proceed to submit. If both fields are empty then alert.
This is what I have in place now after adding some of the input i received earlier today:
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt); return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(billing_name_first,"You must enter your first name to donate")==false)
{billing_name_first.focus();return false;}
else if (validate_required(billing_name_last,"You must enter your last name to donate")==false)
{billing_name_last.focus();return false;}
else if (validate_required(billing_address_street1,"You must enter your billing street address to donate")==false)
{billing_address_street1.focus();return false;}
else if (validate_required(billing_address_city,"You must enter your billing address city to donate")==false)
{billing_address_city.focus();return false;}
else if (validate_required(billing_address_state,"You must enter your billing address state to donate")==false)
{billing_address_state.focus();return false;}
else if (validate_required(billing_address_zip,"You must enter your billing address zip code to donate")==false)
{billing_address_zip.focus();return false;}
else if (validate_required(billing_address_country,"You must enter your billing address country to donate")==false)
{billing_address_country.focus();return false;}
else if (validate_required(donor_email,"You must enter your email address to donate")==false)
{donor_email.focus();return false;}
else if (validate_required(card_number,"You must enter your credit card number to donate")==false)
{card_number.focus();return false;}
else if (validate_required(card_cvv,"You must enter your credit card security code to donate")==false)
{card_cvv.focus();return false;}
else if (validate_required(input1,"Need to enter a donation amount to continue")==false && validate_required(input2, "Need to enter a donation amount to continue")==false)
{
input1.focus();
return false;
}
}
}
This works fine... other than the fact that I get a message that reads error undefined... which i click ok about 2 times then I get the correct alert and instead of allowing me to correct the problem in IE7 and IE8 the form just processes.
Thanks guys any help would do
Matt
If I am understanding correctly, you only want to do the alert if both of the inputs are empty. If that's the case here's a refactoring of your code that will handle that.
function validate_required(field)
{
with (field)
{
if (value==null||value=="")
{
return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(input1)==false && validate_required(input2)==false)
{
alert('Need a donation to continue');
input1.focus();
return false;
}
}
}
take the alert() out of your assessment function- you're trying to do too much at once. a function to determine if input is valid or not should do only that one thing.
determine the state of your inputs first and then do something like
var field1Pass = validate_required(input1);
var field2Pass = validate_required(input2);
if ( !(field1Pass && field2Pass) ) {
alert("Need a donation amount to continue");
// TODO: logic to determine which field to focus on
return false;
}
var msg = "Need a donation amount to continue";
function validate_required(value) {
if(isNaN(value) || value == null || value == "") {
return false;
}
return true;
}
function validate_form(thisform) {
var i1 = validate_required($(thisform.input1).val());
var i2 = validate_required($(thisform.input2).val());
if(!(i1 && i2)) {
alert(msg);
thisform.input2.focus();
return false;
}
}
Look at the jQuery validation plugin. With the plugin it would just be a matter setting up the rules properly. You could get fancier and replace the default messages if you want. Check out the examples.
<script type="text/javascript">
$(function() {
$('form').validate({
'input1': {
required: {
depends: function() { $('#input2').val() == '' }
}
}
});
});
</script>
This sets it up so that input1 is required if input2 is empty, which should be sufficient since if input1 has a value, you don't need input2 and if neither has a value, then it will show your message for input1.
<input type="text" name="input1" />
<input type="text" name="input2" />
Here's my take, with refocusing on the first field that failed:
<body>
<form action="#" onsubmit="return validate(this);">
<input type="text" name="val0" /><br />
<input type="text" name="val1" /><br />
<input type="submit" />
</form>
<script type="text/javascript">
function validate(form) {
var val0Elem = form.val0, val1Elem=form.val1, elementToFocus;
// check fields and save where it went wrong
if (!numeric(val0Elem.value)) {elementToFocus=val0Elem;}
else if (!numeric(val1Elem.value)) {elementToFocus=val1Elem;}
// if there is an element to focus now, some validation failed
if (elementToFocus) {
alert('Enter numbers in both fields, please.')
// using select() instead of focus to help user
// get rid of his crap entry :)
elementToFocus.select();
// ..and fail!
return false;
}
// Helper function, "if a string is numeric":
// 1: it is not 'falsy' (null, undefined or empty)
// 2: it is longer than 0 too (so that '0' can be accepted)
// 3: it passes check for numericality using the builtin function isNaN
function numeric(s) {return (s && s.length>0 && !isNaN(s));}
}
</script>
</body>

Categories