A few days ago, while work­ing on a web page, I got to write my fa­vorite type of code: val­i­da­tion.

jQuery validation

Ha ha. Actually I’d rather floss with a brick than write val­i­da­tion.

Anyway, I was writ­ing val­i­da­tion for an ASP.NET/C# reg­is­tra­tion page. The page has three drop­down lists, each with the same list of courses. Students can reg­is­ter for up to three courses by choos­ing a course in each drop­down list. The val­i­da­tion I was writ­ing needed to pre­vent a stu­dent from reg­is­ter­ing for a course mul­ti­ple times. It seemed like there should be a sim­ple so­lu­tion, but it was­n’t jump­ing out at me, so I started to pseudocode a naive so­lu­tion.

valid if:
    1 != 2 and 
    2 != 3 and 
    3 != 1

Okay, not very el­e­gant. And not eas­ily scal­able if when I’m asked to add a fourth drop­down. I started cod­ing it out a lit­tle more in the hopes of see­ing a pat­tern.

if 1 = "" && 2 = "" && 3 = ""
    valid
if 1 != 2 && 1 != 3
    1 is valid  

Then I had a eureka” mo­ment: I could put the val­ues in an ar­ray, get the count of unique items, and check if the num­ber of val­ues is equal to the num­ber of unique val­ues.

var courses = new[] { ddlCourse1.SelectedValue, ddlCourse2.SelectedValue, ddlCourse3.SelectedValue };
e.IsValid = courses.Length != courses.Distinct().Count();

This works be­cause I don’t care how many du­pli­cates there are, or which val­ues are du­pli­cated. I just want to know if du­pli­cates ex­ist.

However, it’s not quite com­plete. If a stu­dent reg­is­ters for only one course, say History 101”, drop­down list 1 will have the value HI 101” and drop­downs 2 and 3 will be empty strings. Since "" == "", I’ll need to al­low mul­ti­ple empty strings.

IEnumerable courses = new [] { ddlCourse1.SelectedValue, ddlCourse2.SelectedValue, ddlCourse3.SelectedValue };
courses = courses.Where(x => !String.IsNullOrEmpty(x));

e.IsValid = courses.Count() == courses.Distinct().Count();

Boom. And in jQuery:

var courses = $('.Course option:selected').map(function() { 
    if (this.value) {
        return this.value;
    }

    return null;
});

var uniqueCourses = $.grep(courses, function(value, index) {
    return $.inArray(value, courses) === index;
});

e.IsValid = courses.length === uniqueCourses.length;

I still don’t like writ­ing val­i­da­tion, but…it has its in­ter­est­ing mo­ments.