public
Created — forked from Nijikokun/example-user.js

Beautiful Validation... Why have I never thought of this before?!

  • Download Gist
example-user.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var user = {
validateCredentials: function (username, password) {
return (
(!(username += '') || username === '') ? { error: "No Username Given.", field: 'name' }
: (!(username += '') || password === '') ? { error: "No Password Given.", field: 'pass' }
: (username.length < 3) ? { error: "Username is less than 3 Characters.", field: 'name' }
: (password.length < 4) ? { error: "Password is less than 4 Characters.", field: 'pass' }
: (!/^([a-z0-9-_]+)$/i.test(username)) ? { error: "Username contains invalid characters.", field: 'name' }
: false
);
}
};
 
var results = user.validateCredentials('Nijikokun','somepassword');
console.log(results);
readme.md
Markdown

In a recent project I had to validate a form in Javascript, I've done it thousands of times, but during this one instance I had a stroke of ... oh my god I can really do this ... moment. Essentially it cleaned up about 40 lines of code down to about five or six, and ontop of that, you can easily set variables inside your operation or outside, its just beautiful:

      return (
          (!(username += '') || username === '') ? { error: "No Username Given.", field: 'name' }
        : (!(username += '') || password === '') ? { error: "No Password Given.", field: 'pass' }
        : (username.length < 3)                  ? { error: "Username is less than 3 Characters.", field: 'name' }
        : (password.length < 4)                  ? { error: "Password is less than 4 Characters.", field: 'pass' }
        : (!/^([a-z0-9-_]+)$/i.test(username))   ? { error: "Username contains invalid characters.", field: 'name' }
        : false
      );

It's really it's own language if you think about it. It's just so concise and direct.

Basic Validation

Validate existence:

  (!username || username === '')        ? { error: "No Username Given.", field: 'name' }  // Doesn't Exist? Return this
  : false // Otherwise, nothing to return; False is good. It means it passed validation.

Complex Validation

Regular Expressions? Requirements? All easy.

  (!/^([a-z0-9-_]+)$/i.test(username))  ? { error: "Username contains invalid characters.", field: 'name' } // Test username against RegExp, return this on failure
  : false // It passed!

Nesting?

No problemo.

  (!username)   ?
  (
    (!password) ? { error: "Missing Username and Password.", field: ['name', 'pass'] }
    :             { error: "Missing Username", field: 'name' }
  )
  : false 

Complex problems are still simple to solve in the end. It's so beautiful it hurts.

Variable Setting

If you wish to setup variables in a normal manner you can do so on the lines before validation, this only works for things that are not null, undefined, false.

  (username = username.toString())      && 
  (password = password.toString())      &&

Another method in one statement:

  (
    username = username.toString()        && 
    password = password.toString()
  ) &&

Optional Variable Storage? No Problem.

  (
    username = username.toString()        || 
    password = password.toString()        // Password is now set only if username is true.
  ) &&

A better method for this scenario would be to coerce the variable into a string: !(username += "") and check it.

Or simply do it before the return ;)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.