HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Validation on a form in JS

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
formvalidationstackoverflow

Problem

I've got a form that needs validating before the data in the form is added to a service queue:

```
self.ee.on('validateForm', function(formData){

// Validation
var isValid = false;
var validTitle = false;
var validDescription = false;
var validObjectives = false;
var validOutcome = false;
var validHours = false;

if(formData.title==null){
console.log("error on title")
isValid = false;
}
else{
validTitle = true;
console.log("title is valid");
}

if(formData.description==null){
console.log("error on description")
isValid = false;
}
else{
validDescription = true;
console.log("description is valid");
}

if(formData.objectives==null){
console.log("error on objectives")
isValid = false;
}
else{
validObjectives = true;
console.log("objectives is valid");
}

if(formData.outcome==null){
console.log("error on outcome")
isValid = false;
}
else{
validOutcome = true;
console.log("outcome is valid");
}

if(formData.hours== null){
console.log("Error on hours")
isValid = false;

}
else{
validHours = true;
console.log("hours is valid");
}

if(validTitle && validDescription && validObjectives && validOutcome && validHours){
isValid = true;
}

if (isValid) {
self.ee.emit('formIsValid', formData);
} else {
self.ee.emit('formIsInvalid', formData);

Solution

Since you are only checking all of your fields against null, you could add the field names to an array and then loop through the array.

var isValid = true;
var fields  = ['title', 'description', 'objectives', 'outcome', 'hours'];

for ( var i = 0, n = fields.length; i < n; i++ ) {
    key = fields[i];
    if ( formData[key] == null ) {
        console.log("error on " + key);
        isValid = false;
    } else {
        console.log(key + " is valid");
    }
}

Code Snippets

var isValid = true;
var fields  = ['title', 'description', 'objectives', 'outcome', 'hours'];

for ( var i = 0, n = fields.length; i < n; i++ ) {
    key = fields[i];
    if ( formData[key] == null ) {
        console.log("error on " + key);
        isValid = false;
    } else {
        console.log(key + " is valid");
    }
}

Context

StackExchange Code Review Q#59107, answer score: 5

Revisions (0)

No revisions yet.