Common javascript form validation not working - javascript

I've been trying to use the following javascript code to validate several fields on a contact form. The validation works for the first item being validated, the name field, but not the second, the email field. If the name field is filled in, the validation seems to skip over the email field check when it's blank and the form submits.
function validateForm()
{
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
else if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
else
{
return( true );
}
}
Here is the HTML on the contact form:
<FORM name="contact" METHOD="POST" ACTION="thankyou.php" onsubmit="return validateForm()">
<input type="checkbox" name="newsletter" value="YES" width="30" height="30"> Check the box to subscribe to Herb's Newsletter
<input type="text" class="form-control" size=20 name="name" placeholder="Your name" />
<input type="email" class="form-control" name="email" placeholder="Email Address" />
<input class="btn btn-theme btn-subscribe" type="submit" value="Send" />
</form>
Thank you

You seem to be using empty function in your if clauses which doesn't seem to be defined nor it is part of the standard javascript functions. Try getting rid of it:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "") {
alert("Please enter your name.");
document.contact.name.focus();
return false;
} else if (ema == null || ema == "") {
//Check if the email is missing
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
} else {
return true;
}
}
And here's a live demo.

In your code you use else if statement.
Basically what you code does is:
check name -> if that is falsy check email -> if that is falsy move into else condition.
But when the name is true, the if statement will not move to else conditions because it it already satisfied. So if you want to check both, you either separate the statements and make a 5 separate ifs, make it a switch statement or you create one long check. For example:
if ((n == null || n == "" || empty(n)) || ( ema == null || ema == "" || empty(ema) ))
{
alert("Something is missing");
return false;
}
else
{
return( true );
}
or you use multiple ifs:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
return( true );
}
The latter will always return true unless one of the if statements is triggered.
And see answer below about the empty() thing. I don't know what that is and if it messes anything up.

Related

Trying to convert this big if else statement into a loop

Hi I'm trying to make this code more clean. I struggle with arrays and loops and have no idea how to convert this into into a loop. This is javascript for a form on an html page and if they leave a field blank, when they hit submit it should return an alert box and if everything is submitted properly it should confirm with them. There's also a reg exp for an acceptable postal code entry.
function validate()
{
var register = document.forms[0];
if (register.fname.value === "")
{
alert("Please fill out your first name.");
return false;
}
else if(register.lname.value === "")
{
alert("Please fill out your last name.");
return false;
}
else if(register.address.value === "")
{
alert("Please fill out your address.");
return false;
}
else if(register.postal.value ==="")
{
alert("Please enter a valid postal code.");
return false;
}
else if(!checkPostal(register.postal.value))
{
alert("Please enter a valid postal code.");
return false;
}
else if(register.eAddress.value === "")
{
alert("Please fill out your email address.");
return false;
}
return confirm("Is the information correct?");
}
//postal code regExp
function checkPostal()
{
var myReg = /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/ig;
return myReg.test(document.getElementById("postal").value);
}
You can make this a pure HTML solution if you want to reduce javascript:
inputs have a required attr ref
additionally, inputs have a pattern attr ref that supports regex.
This kind of solution lets the browser handle feedback
<form>
<label>first name:
<input type="text" name="fname" required
minlength="1">
</label><br/>
<label>last name:
<input type="text" name="lname" required
minlength="1">
</label><br/>
<label>postal code:
<input type="text" name="zip" required pattern="^[A-Z]\d[A-Z] ?\d[A-Z]\d$"
minlength="1">
</label><br/>
<input type="submit" />
</form>
$.each( $( "#input input" ), function( key, element ) {
if( !$(element).val() ) {
$( "#error" + key ).text( "Input " + $( element ).attr( "name" ) + " is required");
return false;
}
});
Set your message as attribute on each element of the form like this:
<form method="POST" action="submit.php">
<input id="item1" type="text" value="" data-message="My error message" data-must="true">
...//do the same for other elements...
</form>
Now loop like below
var elements = document.forms[0].elements;
for (var i = 0, element; element = elements[i++];) {
if (element.getAttribute("must") && element.value === ""){
alert(element.getAttribute("message"));
return false;
}
}
return confirm("Is the information correct?");

Remove form error with correct input

I just made a registration form which will tell you in red(CSS) letters if something is wrong. However I want this text to go away as soon as the user writes it correctly. How do I do that?
<script>
function validateForm2() {
var usrnm2 = document.getElementById("usrnm2").value;
var passw2 = document.getElementById("passw2").value;
var cnfpassw2 = document.getElementById("cnfpassw2").value;
var age = document.getElementById("age").value;
if (usrnm2 == null || usrnm2 == "") {
document.getElementById("error1").innerHTML = "You must enter a username";
return false;
}
else if (passw2 == null || passw2 == "") {
document.getElementById("error2").innerHTML = "You must enter a password";
return false;
}
else if (cnfpassw2 !== passw2) {
document.getElementById("error3").innerHTML = "Password does not match";
return false;
}
else if (age < 18) {
document.getElementById("error4").innerHTML = "You are not old enough to enter this site"
return false;
}
else {
alert("Congratulations, you have registered successfully!")
}
}
</script>
<script>
function register2() {
validateForm2()
}
</script>
<form>
Username:
<input id="usrnm2" type="text" name="username"><p id="error1"></p>
Password
<input id="passw2" type="password" name="password"><p id="error2"></p>
Confirm Password
<input id="cnfpassw2" type="password" name="confirmpw2"><p id="error3"></p>
Age
<input id="age" type="number" name="age"><p id="error4"></p><br />
<input id="bttn2" type="button" value="Register!" onclick="register2()"><br />
</form>
Separate the validation conditions into single block if statements, and then include a handler for returning the fields to normal when they are entered correctly:
if (field is entered incorrectly) {
document.getElementById("error").innerHTML = "You must enter correctly";
return false;
}
else {
document.getElementById("error").innerHTML = "";
}
...
alert("Congratulations, you have registered successfully!");
You simply need to place the alert after all of the statements - it will execute as long as none of the conditions fail and thus return.

Javascript - Executing all the validation functions on form submit

I am currently working on an Email form and have little experience with javascript but am close to accomplishing what I need but struggling at one point, spent hours trying everything I can find searching and figured someone on here would probably have my answer instantly.
I currently have 3 functions checking a box is filled, email is correct format and passwords match.
If I set each function to run on its own upon clicking submit they work perfectly for their own intended purpose, however I am having trouble working out how to make it so that all 3 functions are run upon hitting submit. My final attempt which seems closest is adding the validateForm function at the bottom of my scripts to run all scripts but this did not seem to work. Hopefully something small I am overlooking, appreciate any help.
HTML:
<form name="registerkeys" form action="form.php" method="post" onsubmit="return validateForm();">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Phone Number: <input type="text" name="phonenumber"><br>
Information on Key: <input type="text" name="keyinfo"><br>
Password: <input type="password" name="password" id="password"></label><br>
Verify Password: <input type="password" name="passwordverify" id="passwordverify"><br>
Password Hint: <input type="text" name="passwordhint"><br>
<textarea rows="5" name="message" cols="30" placeholder="Comments:"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
Javascript:
function validateFill(){
var x=document.forms["registerkeys"]["first_name"].value;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
var x=document.forms["registerkeys"]["last_name"].value;
if (x==null || x=="") {
alert("Last name must be filled out");
return false;
}
var x=document.forms["registerkeys"]["phonenumber"].value;
if (x==null || x=="") {
alert("Phone number must be filled out");
return false;
}
var x=document.forms["registerkeys"]["keyinfo"].value;
if (x==null || x=="") {
alert("Key info must be filled out");
return false;
}
var x=document.forms["registerkeys"]["pass1"].value;
if (x==null || x=="") {
alert("Password must be filled out");
return false;
}
var x=document.forms["registerkeys"]["passwordhint"].value;
if (x==null || x=="") {
alert("Password hint must be filled out");
return false;
}
}
function validateEmail()
{
var x=document.forms["registerkeys"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
function validatePassword(){
var password = document.getElementById("password").value;
var passwordverify = document.getElementById("passwordverify").value;
var ok = true;
if (password != passwordverify) {
alert("Passwords Do not match");
document.getElementById("password").style.borderColor = "#E34234";
document.getElementById("passwordverify").style.borderColor = "#E34234";
ok = false;
}
else {
alert("Passwords Match!!!");
}
return ok;
}
function validateForm(){
var a = validateFill();
var b = validateEmail();
var c = validatePassword();
return a && b && c;
}
Your validateFill() and validateEmail() function should return true at the end.
validateFill() only returns false if validation has not passed, but never true. You should add return true at the end of the function, outside of conditions.
validateEmail() returns false if email is invalid but you are missing the return true if email is valid.
Also, to prevent duplicate popups I suggest that you change your validateForm() to something like this:
function validateForm() {
var a = validateFill();
if (a) var b = validateEmail();
else var b = false;
if (a&&b) var c = validatePassword();
else var c = false;
return a && b && c;
}
So it only checks one function until it passes, and then checks the next.
validateFill() and validateEmail() should return true at the end (right now they return nothing if validation passed.
validatePassword() should return true instead of ok.

JavaScript double form validation

I am new to JavaScript and I have been doing a university assignment based around HTML and JavaScript. In this assignment I was asked to create a number of forms to allows a person to register for some form of educational classes. I was asked to create the form using HTML and to validate the entries using only JavaScript.
What I have been struggling to figure out is how to validate more than one form input using one block of validation (if that is possible), I want to validate both the firstname and familyname inputs using only validateForm.
Here is a segment I have been testing out:
<head>
<script>
function validateForm() {
var x = document.forms["nameform"]["firstname"].value;
if (x == null || x == "") {
alert("first name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="nameform" , action="demo_form.asp" , onsubmit="return validateForm()" , method="post">
<b>First name:</b>
<input type="text" name="firstname">
<br>
<b>Family name:</b>
<input type="text" name="familyname">
<br>
<input type="submit" value="Submit">
</form>
</body>
Any help would be greatly appreciated!
<head>
<script>
function validateForm()
{
var firstname=document.getElementById('txtfirstname');
var familyname=document.getElementById('txtfamilyname');
if (firstname.value=="")
{
alert("first name must be filled out");
return false;
}
if (familyname.value=="")
{
alert("familyname must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="nameform", action="demo_form.asp", onsubmit="return validateForm()", method="post">
<b>First name:</b> <input type="text" id="txtfirstname" name="firstname">
<br>
<b>Family name:</b> <input type="text" id="txtfamilyname" name="familyname">
<br>
<input type="submit" value="Submit">
</form>
</body>
You can check all inputs, store error messages (if any) and return false at the end if there is even one failure.
i.e.
function validateForm() {
var x = document.forms["nameform"]["firstname"].value, errors = [];
if (x == null || x == "") {
errors.push("first name must be filled out");
}
x = document.forms["nameform"]["familyname"].value;
if (x == null || x == "") {
errors.push("family name must be filled out");
}
if(errors.length > 0) { // check if there were any errors
alert(errors.join("\n")); // alert all messages together
return false;
}
}
Couple of possibilities...
<script>
function validateForm()
{
var x=document.forms["nameform"]["firstname"].value;
if (x==null || x=="")
{
alert("first name must be filled out");
return false;
}
x=document.forms["nameform"]["lasttname"].value;
if (x==null || x=="")
{
alert("last name must be filled out");
return false;
}
return true;
}
</script>
will present an alert for each field as it fails validation and return true if all fields are OK.
<script>
function validateForm()
{
var errorString="";
var x=document.forms["nameform"]["firstname"].value;
if (x==null || x=="")
{
errorString+="first name must be filled out\n";
}
x=document.forms["nameform"]["lasttname"].value;
if (x==null || x=="")
{
errorString+="last name must be filled out\n";
}
if(errorString=="")
{
return true;
}
else
{
alert(errorString);
return false;
}
}
</script>
will return a single alert listing all of the fields that have failed validation.
In addition, I always like to use the focus() method on the first field that failed validation to put the cursor in the field that needs correcting.
Try this..
function validateForm()
{
var msg='';
var flag=false;
var x = document.forms["nameform"]["firstname"].value;
if (x == null || x == "")
{
flag = true;
msg = ' First Name '
}
x = document.forms["nameform"]["familyname"].value;
if (x == null || x == "")
{
if(flag==true)
msg = msg + 'And Family Name '
else
msg = msg + ' Family Name ';
flag = true;
}
if (flag==true) {
msg = msg + " must be filled out";
alert(msg);
}
return false;
}
simply store it in multiple variables and have multiple if statements:
<script>
function validateForm() {
// name the variables appropriately
var firstname = document.forms["nameform"]["firstname"].value;
var familyname = document.forms["nameform"]["familyname"].value;
// check if either of them are correct, if not alert and return false.
if (firstname == null || firstname == "") {
alert("first name must be filled out");
return false;
} else if (familyname == null || familyname == ""){
alert("family name must be filled out");
return false;
}
return true;
}
</script>

Need alert for all field in javascript

How to get alert for all empty field. In this bellow code, I am able to get alert for username field. how to get alert for all the fields.
JavaScript Code
function null_field(form_name, field_name) {
var field = document.forms[form_name][field_name].value;
if (field == null || field == "") {
alert("All Field Are Required");
return false;
}
}
Login Form
<form action="login_code.php" method="post" onSubmit="return null_field('login_form', 'username')" name="login_form">
<b>Username: </b><input type="text" name="username" class="field">
<b>Password: </b><input type="password" name="password" class="field">
<input type="submit" value="submit">
</form>
Create a function for the whole form instead:
function valid_form(form_name) {
var form = document.forms[form_name],
fields = form.elements, i = 0, l = fields.length;
for (; i < l; i++)
if (fields[i].value === "") {
alert("All Field Are Required");
return false;
}
return true;
}
For each field, you have to call the function. so, for each input tag, call onsubmit="not_null".
I think link will help you what you need. Hope you are looking for same
http://www.c-sharpcorner.com/blogs/8702/validation-summary-in-javascript.aspx
In raw javascript you could do the following:
function null_field(form_name)
{
for(i=0; i<document.forms[form_name].elements.length; i++){
if (document.forms[form_name].elements[i] == null ||document.forms[form_name].elements[i].value == "" || document.forms[form_name].elements.value == undefined)
{
alert("All Field Are Required");
return false;
}
}
return true;
}
If you need one single alert if there are any empty fields, you can use something like this:
function validate_fields(form_name) {
var has_empty_fields = false;
for (var field in document.forms[form_name].elements) {
if(field == null || field.value == "") {
has_empty_fields = true;
break;
}
}
if (has_empty_fields) {
alert("All Fields Are Required");
return false;
}
return true;
}

Categories