Skip to content

Instantly share code, notes, and snippets.

@Muzietto
Created October 11, 2015 17:41
Show Gist options
  • Save Muzietto/ca06ed7aa4ba41a794ed to your computer and use it in GitHub Desktop.
Save Muzietto/ca06ed7aa4ba41a794ed to your computer and use it in GitHub Desktop.
Validating a form with a writer monad
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>monadic validation</title>
<style>
body { font-family: Verdana; font-size: 1.5em; }
.horizon { width: 500px; margin: 0 auto; padding: 10px; border: 2px solid red; }
.horizon input, .horizon label { margin: 10px; }
.horizon input { width: 400px; height: 2em; }
</style>
<script type="text/javascript">
'use strict';
function writer(couple){
var monad = couple.slice();
var m_empty = '';
var m_append = function(x, y) { return x + y; };
monad.bind = function(faw){
var newCouple = faw(monad[0]);
return writer([newCouple[0], m_append(monad[1], newCouple[1])]);
}
return monad;
}
writer.unit = function(value) { return writer([value, '']); }
function validate() {
var htmlElems = document.getElementsByClassName('validation');
var inputsArray = [].slice.call(htmlElems);
var monad = writer.unit();
inputsArray.forEach(function(item) {
var predicate = new Function('value', 'return ' + item.dataset.predicate);
var isOk = predicate(item.value);
var verdict = item.id + '; ' + item.value + ' --> ' + isOk + '\n';
var faw = function(previousIsOk) { return writer([isOk, verdict]);}
monad = monad.bind(faw);
});
alert(monad[1]);
}
</script>
</head>
<body>
<h1 style="margin-left:20px;">validation using the writer monad</h1>
<div id="mainDiv" class="horizon">
<label for="numericInput">insert a NUMBER</label>
<input type="text" class="validation" id="numericInput" data-predicate="/^[0-9]+$/.test(value)"/>
<label for="booleanInput">insert a BOOLEAN</label>
<input type="text" class="validation" id="booleanInput" data-predicate="/^(true|false)$/.test(value)"/>
<label for="stringInput">insert a STRING containing A</label>
<input type="text" class="validation" id="stringInput" data-predicate="/A+/.test(value)"/>
<input id="btn" type="button" value="VALIDATE" onclick="validate()"/>
</div>
</body>
</html>
@Muzietto
Copy link
Author

Each form input contains its own validation regex inside an HTML5 custom data-predicate attribute. This writer monad is a plain 2-elements JS array equipped with apt unit and bind instance methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment