forms and Java Script validation

What way do you code form validation so that it checks multiple lines.  For example first name and address.   When I click submit I want java script to validate each line.  

I think I need to start a session need some advise when to start if it needs to stop etc

I am using PHP and java script
enigma1234567890Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

wuyinzhiCommented:
you should use input type for each entry, this is the sample code:


<form action=submit.php method=post name=frmregnew onsubmit="return validate();">                              

Name: <input type="text"name=firstname maxlength=255 /><br>            
Address: <input type="text"name=address maxlength=255 /><br>            

<input type=submit name=submit value=submit>
</form>

<script language=javascript type=text/javascript>
function validate()

{      
      
      if (document.frmregnew.firstname.value == "") {
            alert("input first name")
                  document.frmregnew.firstname.focus()
                  return false
      }
            
      if (document.frmregnew.address.value == "") {
            alert("input address")
                  document.frmregnew.address.focus()
                  return false
      }
     return true
}

</script>
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
khan_webguruCommented:
Yup wuyinzhi@ is right but you can change the way to get text box values like below

 
<form action=submit.php method=post name=frmregnew onsubmit="return validate();">                              

Name: <input type="text" id="firstname" name="firstname" maxlength=255 /><br>            
Address: <input type="text" id="address" name="address" maxlength=255 /><br>            

<input type=submit name=submit value=submit>
</form>

<script language=javascript type=text/javascript>
function validate()

{      
      
      if (document.getElementById("firstname").value == "") {
            alert("input first name")
                  document.getElementById("firstname").focus()
                  return false
      }
            
      if (document.getElementById("address").value == "") {
            alert("input address")
                  document.getElementById("address").focus()
                  return false
      }
     return true
}

</script>

Open in new window


Add the code from "<script language=javascript type=text/javascript>" to "</script>" in head section

Hope this will help you.

Thanks,
1
enigma1234567890Author Commented:
I have been following the code from this website but when I try adding the two togeter one for email and name it only does one
0
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

enigma1234567890Author Commented:
0
khan_webguruCommented:
Post the code and we will check the problem
0
khan_webguruCommented:
Use like this

HTML

 
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
var y=document.forms["myForm"]["email"].value;
var atpos=y.indexOf("@");
var dotpos=y.lastIndexOf(".");

if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
  {
  alert("Not a valid e-mail address");
  return false;
  }

}

Open in new window


JAVASCRIPT

 
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" id="fname" name="fname"/>
Email: <input type="text" id="email" name="email"/>
<input type="submit" value="Submit"/>
</form>

Open in new window

0
Ray PaseurCommented:
Just a gentle note about JavaScript form validation.  It may be nice for the clients, and rather than invent your own you might want to learn jQuery (it implements the good parts of JavaScript in easy-to-use ways).  However it is completely useless in terms of data validation for the purposes of getting and keeping the data model on the server.  JavaScript can be turned off or easily bypassed.  The nice people will not do this - only the attackers will.

Information Technology Security is a huge and sprawling topic (The University of Maryland offers a full-time four year college major in IT security) and I cannot begin to give you all that you would need to know in an answer to a question at EE.  But I can tell you that your site WILL get destroyed if you do not filter the external data adequately via the server-side scripts after it has been submitted.  It is just a matter of time.

The correct mantra is "Accept only known good values."  Learn about the PHP function filter_var().  One simple example is shown in the code snippet.  You can test it on my server here:
http://www.laprbass.com/RAY_email_validation.php

Each element of a form should be associated with a validation routine.  Unit testing is important for the validation routines.

HTH, ~Ray
<?php // RAY_email_validation.php
error_reporting(E_ALL);


// A FUNCTION TO TEST FOR A VALID EMAIL ADDRESS, RETURN TRUE OR FALSE
function check_valid_email($email)
{
    // IF PHP 5.2 OR ABOVE, WE CAN USE THE FILTER
    // MAN PAGE: http://us3.php.net/manual/en/intro.filter.php
    if (strnatcmp(phpversion(),'5.2') >= 0)
    {
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) return FALSE;
    }
    // IF LOWER-LEVEL PHP, WE CAN CONSTRUCT A REGULAR EXPRESSION
    else
    {
        $regex
        = '/'                       // START REGEX DELIMITER
        . '^'                       // START STRING
        . '[A-Z0-9_-]'              // AN EMAIL - SOME CHARACTER(S)
        . '[A-Z0-9._-]*'            // AN EMAIL - SOME CHARACTER(S) PERMITS DOT
        . '@'                       // A SINGLE AT-SIGN
        . '([A-Z0-9][A-Z0-9-]*\.)+' // A DOMAIN NAME PERMITS DOT, ENDS DOT
        . '[A-Z\.]'                 // A TOP-LEVEL DOMAIN PERMITS DOT
        . '{2,6}'                   // TLD LENGTH >= 2 AND =< 6
        . '$'                       // ENDOF STRING
        . '/'                       // ENDOF REGEX DELIMITER
        . 'i'                       // CASE INSENSITIVE
        ;
        if (!preg_match($regex, $email)) return FALSE;
    }

    // FILTER_VAR OR PREG_MATCH DOES NOT TEST IF THE DOMAIN IS ROUTABLE
    $domain = explode('@', $email);

    // MAN PAGE: http://us3.php.net/manual/en/function.checkdnsrr.php
    if ( checkdnsrr($domain[1],"MX") || checkdnsrr($domain[1],"A") ) return TRUE;

    // EMAIL IS NOT ROUTABLE
    return FALSE;
}


// DEMONSTRATE THE FUNCTION IN ACTION
$e = '';
if (!empty($_GET["e"]))
{
    $e = $_GET["e"];
    if (check_valid_email($e))
    {
        echo "<br/>VALID: $e \n";
    } else
    {
        echo "<br/>BOGUS: $e \n";
    }
}

// END OF PROCESSING - PUT UP THE FORM
$form = <<<ENDFORM
<form method="get">
TEST A STRING FOR A VALID EMAIL ADDRESS:
<input name="e" value="$e" />
<input type="submit" />
</form>
ENDFORM;

echo $form;

Open in new window

0
enigma1234567890Author Commented:
the code i want is something like

function validateform()
 if firstname ==""
Place redthest at right of form name firstname stating you didnt  enter first name
change background to yellow
else do nothing

if lastname ==""
Send alert
Place red text at the right of form name lastname stating you didnt enter last name
change background to yellow
else do

<form id="formA" name ="formA" action="result.php" onsubmit="return validateform();" method="post">

The problem is the code just keeps performing the first step and then sending the data

0
Ray PaseurCommented:
You can probably find something like what you want in jQuery plug-ins -- there are a lot of them and they implement mostly the "good parts" of JavaScript.

The code snippet shows a design pattern that will allow you to have the server-side tests.  The CSS is used to control visibility of the error messages and hints.

HTH, ~Ray
<?php // RAY_form_highlight_errors.php
error_reporting(E_ALL);


// DEMONSTRATE HOW TO HIGHLIGHT ERRORS IN FORM INPUT
// CLIENT IS ASKED TO PUT IN A VALUE
// IF THE VALUE FAILS OUR TEST WE SHOW AN ERROR MESSAGE
// WE PUT A MARKER NEXT TO THE INPUT CONTROL ON THE FORM
// SEE http://www.w3schools.com/CSS/pr_class_visibility.asp


// THESE CONDITIONS ARE SET FOR THE INITIAL ENTRY
$error_any = 'hidden';
$error_abc = 'hidden';
$error_xyz = 'hidden';

// CAPTURE AND NORMALIZE THE POST VARIABLES, IF ANY
$abc = (isset($_POST["abc"])) ? trim(strtoupper($_POST["abc"])) : NULL;
$xyz = (isset($_POST["xyz"])) ? trim(strtoupper($_POST["xyz"])) : NULL;

// IF ANYTHING WAS POSTED, VALIDATE IT
if (!empty($_POST))
{
    // VALIDATE THE 'abc' FIELD
    if ($abc != 'ABC')
    {
        $error_any = 'visible';
        $error_abc = 'visible';
        $abc       = NULL;
    }

    // VALIDATE THE 'xyz' FIELD
    if ($xyz != 'XYZ')
    {
        $error_any = 'visible';
        $error_xyz = 'visible';
        $xyz       = NULL;
    }

    // DO WE HAVE INPUT FREE FROM ANY ERRORS?
    if ($error_any != 'visible')
    {
        echo "CONGRATULATIONS";
        die();
    }
}

// IF NOTHING WAS POSTED, OR IF THERE ARE ERRORS, WE NEED NEW CLIENT INPUT
$form = <<<ENDFORM
<style type="text/css" media="all">
.error_any { visibility:$error_any; }
.error_abc { visibility:$error_abc; }
.error_xyz { visibility:$error_xyz; }
</style>
<pre>
<form method="post">
<span class="error_any">PLEASE CORRECT THE FOLLOWING ERRORS</span>
<span class="error_abc">YOU MUST ENTER 'abc' IN THIS FIELD</span>
PLEASE ENTER "ABC" HERE: <input name="abc" value="$abc" />
<span class="error_xyz">YOU MUST ENTER 'xyz' IN THIS FIELD</span>
PLEASE ENTER "XYZ" HERE: <input name="xyz" value="$xyz" />
<input type="submit" />
</form>
ENDFORM;

// WRITE THE FORM WITH THE APPROPRIATE CSS STYLES ON THE ERROR MESSAGE FIELDS
echo $form;

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JScript

From novice to tech pro — start learning today.