What is the best way to do multiple validations with different error messages on single field using bacon.js?

212 Views Asked by At

I want validate single field using few rules

There is simple example. This is html form:

<div class="form-group">
  <label for="fullName">Name</label>
  <input type="text" class="form-control" id="fullName" placeholder="Enter name">
</div>
<div class="form-group">
   <div id="fullNameErrors"></div>
</div>

And this my validation function:

function checkForm() {
    $("#fullNameErrors").hide();
    var fullName = $("#fullName").val();
    if (fullName.length < 4) {
        $("#fullNameErrors").show().html("Name too short");
    }
    var parts = fullName.split(" ");
    if (parts.length!=2) {
        $("#fullNameErrors").show().html("First name and last name expected");
    }
    if (parts[0].length<3) {
        $("#fullNameErrors").show().html("First name to short");
    }
}

When a field is changed I call checkForm().

How the same idea can be implemented in FRP way using Bacon.js?

1

There are 1 best solutions below

0
On

You can map the validation errors to Bacon.Error objects like this:

var $errors = $("#fullNameErrors");
var $fullName = $("#fullName");

var nameChanges = $fullName.asEventStream("input").flatMapLatest(function() {
    var fullName = $fullName.val();
    if (fullName.length < 4) {
        return new Bacon.Error("Name too short");
    }
    // other validations here
    return fullName;
});

nameChanges.onValue(function(fullName) {
    console.log("Name ok: " + fullName);
    $errors.empty();
});

nameChanges.onError(function(error) {
    $errors.text(error);
});

Try it with the JSFiddle. See more details about Bacon.js error handling https://github.com/baconjs/bacon.js#errors