HostNed Community

WEB DESIGN DISCUSSIONS => Scripting => Topic started by: Dynaweb on March 04, 2006, 03:44:31 AM

Title: [How To] Making a form field required
Post by: Dynaweb on March 04, 2006, 03:44:31 AM
Let's say you have a web form and you want to make a couple of the fields required.  To keep this as simple as possible we will involve only three fields, "Name", "Email", and "Message".  In this example, all three fields will be required.

Here is your initial form:
<form method="post" action="whatevermailscript.php">
<input maxlength="256" size="35" name="email">
<p>Comments:  <textarea cols="55" name="Comment">  </textarea></p>
<p><input type="submit" value="Send" name="submit">
</form>

You might have noticed I didn't put a Reset button in there.  I think they are stupid, so I dont use them.

Now we need to plug in the validation.  We do this with good old JavaScript!  We will use a function, define the variables (the fields) and call for it on submission (when you click send).  So here we go.

Step 1. Add this in your html form page between the <head></head> tags:
<script>
function ValidateContactForm()
{
    var name = document.ContactForm.Name;
    var email = document.ContactForm.Email;
    var comment = document.ContactForm.Comment;

    if (email.value == "")
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
    if (email.value.indexOf("@", 0) < 0)
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
    if (email.value.indexOf(".", 0) < 0)
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
    if (comment.value == "")
    {
        window.alert("Please enter a description or comment.");
        comment.focus();
        return false;
    }
    return true;
}
</script>


Step 2. Add this as an attribute in the form tag:
onsubmit="return ValidateContactForm();"

Finished Product

<html>

<head>
<title>Form Validation Example</title>

<script>
function ValidateContactForm()
{
    var name = document.ContactForm.Name;
    var email = document.ContactForm.Email;
    var comment = document.ContactForm.Comment;

    if (name.value == "")
    {
        window.alert("Please enter your name.");
        name.focus();
        return false;
    }
   
    if (email.value == "")
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
    if (email.value.indexOf("@", 0) < 0)
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
    if (email.value.indexOf(".", 0) < 0)
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
    if (comment.value == "")
    {
        window.alert("Please provide a detailed description or comment.");
        comment.focus();
        return false;
    }
    return true;
}
</script>
</head>

<body>
Use this form to leave a comment:
<form method="post" action="whatevermailscript.php"
name="ContactForm" onsubmit="return ValidateContactForm();">
    <p>Name: <input type="text" size="65" name="Name"></p>
    <p>E-mail Address:  <input type="text" size="65" name="Email"></p>
    <p>Comments:  <textarea cols="55" name="Comment">  </textarea></p>
    <p><input type="submit" value="Send" name="submit">
    <input type="reset" value="Reset" name="reset"></p>
</form>

</body>
</html>


I hope you will be able to take this example form validator and use it in your own scripts successfully.  Enjoy  ;)
Title: Re: [How To] Making a form field required
Post by: giovas on February 12, 2009, 06:33:03 PM
Hi, this doesn't seem to work for me. I must be missing something...... Here is the validation code:



<script>
function ValidateContacto)
{
    var nombre = document.Contacto.Nombre;
var apellidoPaterno = document.Contacto.ApellidoPaterno;
    var email = document.Contacto.Email;
var ciudad = document.Contacto.Ciudad;
var estado = document.Contacto.Estado;
var pais = document.Contacto.Pais;

    if (email.value == "")
    {
        window.alert("Por favor escriba su dirección de E-Mail.");
        email.focus();
        return false;
    }
    if (Email.value.indexOf("@", 0) < 0)
    {
        window.alert("Por favor vuelva revise que su dirección de E-Mail este escrita correctamente.");
        Email.focus();
        return false;
    }
    if (Email.value.indexOf(".", 0) < 0)
    {
        window.alert("Por favor vuelva revise que su dirección de E-Mail este escrita correctamente.");
        Email.focus();
        return false;
    }
    if (Nombre.value == "")
    {
        window.alert("Por favor escriba su Nombre.");
        Nombre.focus();
        return false;
    }
    if (ApellidoPaterno.value == "")
    {
        window.alert("Por favor escriba su Apellido Paterno.");
        ApellidoPaterno.focus();
        return false;
    }
    if (Ciudad.value == "")
    {
        window.alert("Por favor escriba su Ciudad.");
        Ciudad.focus();
        return false;
    }
    if (Estado.value == "")
    {
        window.alert("Por favor escriba su Estado.");
        Estado.focus();
        return false;
    }
    if (Pais.value == "")
    {
        window.alert("Por favor escriba su Pais.");
        Pais.focus();
        return false;
    }
    return true;
}
</script>



And this is the form code:



<form action="sendmail.php" method="post" name="Contacto" id="Contacto" onsubmit="return ValidateContacto();">
          <table width="91%" border="0">
            <tr>
              <td width="29%" class="style1"><div align="right">Deseo:</div></td>
              <td width="71%" class="style1"><label>
                <input name="InfoDiagPrec" type="checkbox" class="style1" id="InfoDiagPrec" />
                Recibir más información sobre lo que puedo hacer en <span class="style7">D</span><span class="style19">iag</span><span class="style7">P</span><span class="style19">rec</span></label></td>
            </tr>
            <tr>
              <td class="style1">&nbsp;</td>
              <td class="style1"><input name="InfoMembresias" type="checkbox" class="style1" id="InfoMembresias" />
Recibir más información sobre las membresias</td>
            </tr>
            <tr>
              <td class="style1"><div align="right"></div></td>
              <td class="style1"><input name="Contratar" type="checkbox" class="style1" id="Contratar" />
                Contratar</td>
            </tr>
            <tr>
              <td class="style1"><div align="right">Nombre:</div></td>
              <td class="style1"><label>
                <input name="Nombre" type="text" class="style1" id="Nombre" />
                <span class="style20">*</span>              </label></td>
            </tr>
            <tr>
              <td class="style1"><div align="right">Apellido Paterno:</div></td>
              <td class="style1"><input name="ApellidoPaterno" type="text" class="style1" id="ApellidoPaterno" /> <span class="style20">*</span></td>
            </tr>
            <tr>
              <td class="style1"><div align="right">Apellido Materno:</div></td>
              <td class="style1"><input name="ApellidoMaterno" type="text" class="style1" id="ApellidoMaterno" /></td>
            </tr>
            <tr>
              <td class="style1"><div align="right">E-Mail:</div></td>
              <td class="style1"><input name="Email" type="text" class="style1" id="Email" /> <span class="style20">*</span></td>
            </tr>
            <tr>
              <td class="style1"><div align="right">Teléfono:</div></td>
              <td class="style1"><input name="Lada1" type="text" class="style1" id="Lada1" size="3" maxlength="3" />
                -
                <input name="Lada2" type="text" class="style1" id="Lada2" size="3" maxlength="3" />
                -
                <input name="Telefono" type="text" class="style1" id="Telefono" size="8" maxlength="8" /></td>
            </tr>
            <tr>
              <td class="style1"><div align="right">Celular:</div></td>
              <td class="style1"><input name="Lada3" type="text" class="style1" id="Lada3" size="3" maxlength="3" />
                -
                <input name="Lada4" type="text" class="style1" id="Lada4" size="3" maxlength="3" />
                -
                <input name="Celular" type="text" class="style1" id="Celular" size="8" maxlength="8" /></td>
            </tr>
            <tr>
              <td class="style1"><div align="right">Ciudad:</div></td>
              <td class="style1"><input name="Ciudad" type="text" class="style1" id="Ciudad" /> <span class="style20">*</span></td>
            </tr>
            <tr>
              <td class="style1"><div align="right">Estado:</div></td>
              <td class="style1"><input name="Estado" type="text" class="style1" id="Estado" /> <span class="style20">*</span></td>
            </tr>
            <tr>
              <td class="style1"><div align="right">País:</div></td>
              <td class="style1"><input name="Pais" type="text" class="style1" id="Pais" /> <span class="style20">*</span></td>
            </tr>
            <tr>
              <td valign="top" class="style1"><div align="right">Comentarios:</div></td>
              <td class="style1"><label>
                <textarea name="Comentarios" cols="45" rows="5" class="style1" id="Comentarios"></textarea>
              </label></td>
            </tr>
            <tr>
              <td class="style1"><span class="style20">*Campo Obligatorio</span></td>
              <td class="style1">&nbsp;</td>
            </tr>
            <tr>
              <td colspan="2" align="center" class="style1"><label>
                <input type="submit" name="button" id="button" value="Enviar" />
              </label></td>
            </tr>
          </table>
        </form>

Title: Re: [How To] Making a form field required
Post by: Dynaweb on February 13, 2009, 12:52:53 PM
You have an error in your Javascript.  Change

function ValidateContacto)

to

function ValidateContacto()
Title: Re: [How To] Making a form field required
Post by: ckmatthews on June 19, 2015, 11:38:22 PM
Is this code still good with all the recent updates?

I have followed this but I have several fields and added the variables and requirements for each but when I click on "ok" after the warning box comes up it sends the form to email anyway even though it is not completely filled out.

Any thoughts?
Title: Re: [How To] Making a form field required
Post by: Dynaweb on June 20, 2015, 11:21:54 AM
I can take a look at this for you.  Please attach your code in reply and state which browser you are using.
Title: Re: [How To] Making a form field required
Post by: ckmatthews on June 25, 2015, 08:45:47 AM
Thanks for your quick response.  I did finally get it to work.  I don't remember now what I had wrong but I fixed it and it works for me now.  If I remember I had to change the name of ValidateContactform to Validateform to match the name of my form I am using.
Again, thanks for your quick response.
Title: Re: [How To] Making a form field required
Post by: Dynaweb on June 25, 2015, 04:17:35 PM
Glad to hear you got it working!