user3212924
user3212924

Reputation: 21

Meaning of JavaScript form validation code?

I have to explain how a specific Javascript code validates a web form, but I am stuck with what some of the features do, most specifically this section of the code. I understand that the first line defines that the rest of the section should only run if the field Field1 of the form ExampleForm is left empty, but I do not know what purpose the rest of the code serves. All I know is that msg is a variable created earlier in the document with an empty default value, and that result is another variable with a default value of true. Can anyone help me out by explaining what each line does?

if (document.ExampleForm.Field1.value=="") {
msg+="You must enter your name \n";
document.ExampleForm.name.focus();
document.getElementById('Field1').style.color="red";
result = false;
}

Upvotes: 0

Views: 119

Answers (2)

George Mauer
George Mauer

Reputation: 122112

So this would in part depend on what other code is on the page. For example document.ExampleForm is not part of the DOM and seems to be something someone kludged onto your page.

Overall I would say this is pretty bad code that makes a ton of assumptions that won't necessarily hold up written by someone who doesn't understand in-browser javascript very well, but let's go with it

//if the value in this variable is falsy (false, empty, or 0)
if (document.ExampleForm.Field1.value=="") {
    //Append this to the msg string. Note \n is usually used 
    //to indicate "new line" but wont' do anything on the web since that's not how line breaks
    //work on the web
    msg+=”You must enter your name \n”;
    //Invoke the `focus` field on this variable. From the context I assume this is
    //a DOM node so you are basically focusing it in the browser
    document.ExampleForm.name.focus();
    //Set the font color of '#Field1' to red
    document.getElementById('Field1').style.color=”red”;
    //Presumably result is something that tells you true/false did the validation succeed.
    //set it to false to indicate failure.
    result = false;
}

My guess about what document.ExampleForm is that it depends on some undocumented behavior of an old browser to add anything with id=ExampleForm to the document element. But really I have no idea. Maybe you have some code elsewhere that creates that variable. Either way its a horrible idea and should get someone yelled at.

Upvotes: 0

Sterling Archer
Sterling Archer

Reputation: 22405

In plain english:

If the document form field value is equal to an empty string, set the error message to msg, then focus on the element, and give is a red color so the user knows it's an error, and set the result to false, for whatever you're going to use that for later in your code/function.

Upvotes: 2

Related Questions