Skip to content Skip to sidebar Skip to footer

Homework, Javascript, Form Validation

I need to do a javascript form validation. I would like to validate each field as the user clicks or tabs to the next field. (onBlur ?) I have to validate the email for the correc

Solution 1:

The simplest solution is to include your events within the element markup. This approach has fallen out of favor among most web developers, but if you're prevented from using something like jQuery or prototype, and the assignment is homework, the following should be fine.

Keep in mind that using strictly on onblur approach prevents your from checking whether required fields have been left blank, so you generally also want to validate the entire form when the submit button is clicked.

<scripttype="text/javascript">functionvalidateMiddleName() {
   // get element, do some validationif(!valid) {
    alert("invalid middle name");
   }
 }

 functionvalidateForm() {
    validateFirstName();
    validateMiddleName();
    validateLastName();
    //etc...
 }
 </script><formonsubmit="validateForm()"><inputtype="text"name="txtMiddle"VALUE=""SIZE="5"MAXLENGTH="3"onBlur="validateMiddleName()"/></form>

Solution 2:

Yes, onBlur would work, but that tends to get a bit annoying. Generally, validation is done when the user attempts to submit the form.

<scripttype="text/javascript>
function ValidateEmail( id )
{
    var at = '@';
    var dot = '.';
    var lat = id.value.indexOf(at);
    var lstr = id.value.length;
    var ldot = id.value.indexOf(dot);

    if ( (id.value == null) || (id.value == "") ) returnfalse;
    if ( id.value.indexOf(at) == -1 ) returnfalse;
    if ( (id.value.indexOf(at) == -1) || (id.value.indexOf(at) == 0) || (id.value.indexOf(at) == lstr) ) returnfalse;
    if ( (id.value.indexOf(dot) == -1) || (id.value.indexOf(dot) == 0) || (id.value.indexOf(dot) == lstr) ) returnfalse;
    if ( id.value.indexOf(at,(lat+1)) != -1 ) returnfalse;
    if ( (id.value.substring(lat-1,lat) == dot) || (id.value.substring(lat+1,lat+2) == dot) ) returnfalse;
    if ( id.value.indexOf(dot,(lat+2)) == -1 ) returnfalse;
    if ( id.value.indexOf(' ') != -1 ) returnfalse;
    if ( lstr >320 ) returnfalse;
    if ( lat > 64 ) returnfalse;
    if ( (lstr - lat) > 255 ) returnfalse;

    returntrue;
}

functionValidateForm()
{
    var nameID = document.myform.name;
    var emailID = document.myForm.email;

    if ( (nameID.value == null) || (nameID.value == "") )
    {
        alert( "Please fill in your name." );
        nameID.focus();
        nameID.select();
        returnfalse;
    }

    returnValidateEmail( emailID );
}
</script><formname="myForm"onSubmit="return ValidateForm()"action="#"><inputtype="text"name="name"></input><inputtype="text"name="email"></input></form>

Post a Comment for "Homework, Javascript, Form Validation"