Serious question - best form validation method

Hello, everyone,

I have a question that I would like as much input from as many people who truly understand JavaScript as I can get.

When validating a form, is it a best practice to refer to the form, or send the form as an object to the function that will perform the validation?

onSubmit = "return checkValues(this.form);"
function checkValues(formObj){
  if(formObj.firstField.value === ""){ alert("HEY!  FILL THAT OUT!"); }
 }

OR

onSubmit = "return checkValues();"
function checkValues(){
  if(document.forms[0].firstField.value === ""){ alert("HEY!  FILL THAT OUT!"); }
  }

Which is the BEST way to validate a form?

V/r,

:slight_smile:

Hey WolfShade,

Personally I’d go with the first example. The less your methods know about the outside world the better - it makes them easier to test and less likely to break when you change things. If you went with your second example and then changed the page at some point (eg. adding a new form before the existing one) then you’d have to modify your checkValues function.

[off-topic]By the way, what does the V/r mean at the end of your posts?[/off-topic]

Well, I just used document.forms[0] as pseudo-code. It could just as easily have been document.forms["formName"].

I work for the US Dept of Defense, and a lot of the people I correspond with are in military service. Most will sign their emails with “V/r” or “VR” to indicate “Very respectfully”. It’s something that I just started doing and got used to (and I like it). :smile:

V/r,

:slight_smile:

EDIT: Good point, though, so I’m going to edit the original post to reflect that. Thanks, @fretburner!

EDIT: NO I’M NOT!!! The edit icon is not available… so… :frowning:

UPDATE: BTW… the reason why I’m asking is because I’m asking for CF help on the Adobe forums, and one person who has responded indicated that passing the form object isn’t a good idea. While I absolutely trust said person’s knowledge of CF, I’m not entirely sure of said person’s JS knowledge. Now, most people that I know from the SPF JS forum, I totally trust their JS knowledge.

1 Like

Sure, but even if you refer to the form by name, if you change that name it still means multiple places in your code that need updating rather than just your event handler. I believe that it’s a good principle to avoid your functions having side-effects as far as it’s possible - you pass in what the function needs, and get back a result. Plus, as I said before, the more tightly you couple your code to the markup, the less easy it is to reuse.

1 Like

The standard practice for referring to forms is via a unique identifier on the form, from where all elements are easily accessible via the [elements][1] collection.

Using your sample code as an example:

function checkValues(evt) {
    var form = this,
        elements = form.elements,
        isValid = true;
    if(elements.firstField.value === "") {
        isValid = false;
        alert("HEY!  FILL THAT OUT!");
    }
    return isValid; // prevent form submission if not valid
}
var form = document.getElementById('userDetails');
form.onsubmit = checkValues;

Mind you, with HTML5 being widely supported now we can validate forms with no involvement of JavaScript at all.

<input name="firstField" required>

Simple as that.

Further details on types of built-in validation can be found at http://diveintohtml5.info/forms.html
[1]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements

Just curious: if you’re not actually utilising evt, why set it as an argument of the function?

I’m very slowly and cautiously making my way towards HTML5, although I will probably NEVER use built-in validation. I’m too OCD and anal-retentive. Almost pedantic.

Sadly, the URL you suggest is (currently) being blocked by DoD. I have submit an official request for review of the site. If it passes their muster, then I’ll be sure to check it out. Thanks!

My preferred way of validation (and I’ll try to keep it short) is:

<input type=“button” onclick=“return checkValues(this.form);”>

function checkValues(formObj){
  var warn = "";
  if(formObj.firstField.value === ""){ warn += "Please fill out the first field.\n"; }
  if(formObj.secondField.value === ""){ warn += "Please fill out the second field.\n"; }
  if(formObj.thirdField.selectedIndex === 0){ warn += "Please select third field.\n"; }

  if(warn !== ""){
    alert(warn); return false;
    }
  else{
    formObj.submit();
    }
  }

The thing I like about this method is the fact that I don’t have to set any variable to false for every failed section. If the variable warn is blank, all is good; if it isn’t, FAIL.

V/r,

:slight_smile:

UPDATE: DoD response to request - “There are many other good resources for HTML5 research; we don’t see any .info domains being authorized anytime soon.”

Sigh.

:slight_smile:

1 Like

Am I allowed to post a screenshot of the page?

Edit-Do you have a browserstack account?

Which page? I can’t imagine there are any rules against it.

Edit - no, I do not. And if browserstack is run by the same people as stackoverflow, I don’t want one. stackoverflow is more of a popularity contest than a support forum.

V/r,

:slight_smile:

Agreed. I didn’t think they were run by the same people though…?

Anyway I changed some CSS rules and did some paint editing…here is the validation part.

Much appreciated. I’d still rather do validation the old-school way. :man: Yes, I can be a bit of a control freak. :smile:

V/r,

:slight_smile:

Here’s a weird thing. One of the forms (the only one I’ve tested, so far) I’ve set so that it will stringify all element values and do an alert. Everything is blank.

Pseudo code:

<input type=“button” onclick=“alert(JSON.stringify(this.form));” />

<input type="text" name="firstName" id="firstName" value="Aloishus" />
<input type="text" name="lastName" id="lastName" value="Smith" />

This is alerting the following:

{"0":{},"1":{}}

Shouldn’t they have actual values?

V/r,

:slight_smile:

I hate to keep dragging this out. Since this is now a different issue, I’ll start a new thread.

V/r,

:slight_smile:

The evt variable acts as a handy shorthand. Later on we may also make use of the event variable, but until then it serves to say that this function is triggered as an event.

On the other hand, better naming of the function will remove the need for such things too. Event handlers commonly have a handler name in their title to help distinguish what they are.

function validateFormHandler() {
    ...
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.