jFluent - Fluent Style jQuery Validation Plugin

Purpose

jFluent is a light-weight validation framework for client-side validation. It is a jQuery plugin that can be used in ASP .NET MVC. It can also be used in standard (or mobile) HTML websites (see section explaining use).

The source code is a free download. You can extend/modify the framework if needed.

JSFiddle demo of plugin:

http://jsfiddle.net/e3sfj/1/

Implementation

jFluent is implemented as a jQuery plugin with the following rules:

RuleInput typeParameters
CreditCardtexterrorMessage : The error message
EmailtexterrorMessage : The error message
ISOCurrencyCodetexterrorMessage : The error message
NotNullOrEmptytexterrorMessage : The error message
IsAlphatexterrorMessage : The error message
alphaUnicodeRange : The alphaUnicode range (a-zA-Z if null)
IsNumerictexterrorMessage : The error message
numericUnicodeRange : The numeric Unicode range (0-9 if null)
IsAlphaNumerictexterrorMessage : The error message
alphaUnicodeRange : The alphaUnicode range (a-zA-Z if null)
numericUnicodeRange : The numeric Unicode range (0-9 if null)
NotNulltexterrorMessage : The error message
Lengthtextlength : The length (number)
errorMessage : The error message
LengthGreaterThantextlength : The length (number)
errorMessage : The error message
LengthLessThantextlength : The length (number)
errorMessage : The error message
LengthBetweentextlowerLimit : The lower limit oflength (number)
upperLimit : The upper limit oflength (number)
exclusive : Not including thelimits (boolean)
errorMessage : The error message
Equaltextitem : The item to compare the equality to
errorMessage : The error message
NotEqual item : The item to compare the inequality to
errorMessage : The error message
GreaterThantextitem : The compare item (number)
orEqual : Inclusive of item(boolean)
errorMessage : The error message
LessThantextitem : The compare item (number)
orEqual : Inclusive of item(boolean)
errorMessage : The error message
BetweentextlowerLimit : The lower limit(number)
upperLimit : The upper limit(number)
exclusive : Not including the limits (boolean)
errorMessage : The error message
MatchestextregExp : The regular expression pattern to match
errorMessage : The error message
SelectRequiredradio, checkboxfunc : The validation function * that receives the selected value (null if no selection)
errorMessage : The error message
Requiredtext, selectfunc : The validation function * that receives the (selected) value
errorMessage : The error message

* - The validation function should return true or false.

Screen shot

jFluent.jpg

Standard (or mobile) HTML website

Create span elements for input elements which are going to be validated. Eg.

<span class="field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span>

for input element

<input type="text" id="Email" />

These span elements will contain the validation error messages for that input element.

If you want a common single error message for an input field, you can place the message inside the span e.g.:

<span class="field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true">Common single error message here</span>

Add below CSS styles to a style sheet in your site and reference that style sheet in your page.

.field-validation-error {
color: #ff0000;
}

.field-validation-valid {
display: none;
 
If you want a Validation Summary on your page, add the below html where you want it to be displayed:
 
<div class="validation-summary-valid" data-valmsg-summary="true"><ul><li style="display:none"></li></ul></div>
 
Add below CSS styles to your stylesheet:
 
.validation-summary-errors {
color: #e80c4d;
font-weight: bold;
font-size: 1.1em;
}
.validation-summary-valid {
display: none;
}
 
 
* - Create jFluent Rules and call $.jFluentValidate() as shown in the section below. 
 
ASP .NET MVC

The plugin can be used in ASP .NET MVC as shown below.

The Register Model:

RegisterModel.jpg

In the Register.cshtml page:

@model MvcApplication1.Models.RegisterModel
@{

ViewBag.Title = "Register";

}

<h2>Create a New Account</h2>

<p>

Use the form below to create a new account.

</p>

@*Include jQuery*@

<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>

@*Include jFluent*@

<script src="@Url.Content("~/Scripts/jFluent.js")" type="text/javascript"></script>

<script type="text/javascript">

//Fluent Rules for the Register page

function RegisterRules() {

$("#UserName").NotNullOrEmpty("User name cannot be null or empty")

              .Matches("^([A-z]+\\s*)+$", "User name should be alpha with spaces only");

$("#Email").NotNullOrEmpty("Email cannot be null or empty")

           .Email("Email address is not valid");

$("#Password").NotNullOrEmpty("Password cannot be null or empty")

              .LengthGreaterThan(8, false, "Password should be more than 8 char long")

   .Required(function (password) {

        var userName = $("#UserName").val();

        return userName != '' ? password.indexOf(userName) == -1 : true;

   }, "User name cannot be a part of the password.");

$("#ConfirmPassword").NotNullOrEmpty("Confirm password cannot be null or empty")

                     .Required(function (confirmPassword) {

                         return confirmPassword == $("#Password").val();

                     }, "Password and confirm do not match.");

$("#IsProfessional").SelectRequired(function (isPro) {

                        return isPro == "True";

                     }, "Should be a professional");

$("#IsAdult").SelectRequired(function (isAdult) {

      return isAdult == "true";

}, "Should be 18 years or older");

$("#SelectedProfessionId").Required(function (profession) {

var selectedIsPro = $("input:radio[name=IsProfessional]:checked").val();

if (selectedIsPro == "True") {

return profession != "-1";

}

return true;

}, "Should select a profession");

}

$(document).ready(function () {

//Add the Rules to jFluent

$.jFluentRules(RegisterRules);

$(document).submit(function (e) {

//Call jFluent validation

if (!$.jFluentValidate()) {

alert('validation failed!');

e.preventDefault();

}

});

});

</script>

@using (Html.BeginForm()) {

@Html.ValidationSummary()

<div>

<fieldset>

<legend>Account Information</legend>

<div class="editor-label">

@Html.LabelFor(m => m.UserName)

</div>

<div class="editor-field">

@Html.TextBoxFor(m => m.UserName)

@Html.ValidationMessageFor(m => m.UserName)

</div>

<div class="editor-label">

@Html.LabelFor(m => m.Email)

</div>

<div class="editor-field">

@Html.TextBoxFor(m => m.Email)

@Html.ValidationMessageFor(m => m.Email)

</div>

<div class="editor-label">

@Html.LabelFor(m => m.Password)

</div>

<div class="editor-field">

@Html.PasswordFor(m => m.Password)

@Html.ValidationMessageFor(m => m.Password)

</div>

<div class="editor-label">

@Html.LabelFor(m => m.ConfirmPassword)

</div>

<div class="editor-field">

@Html.PasswordFor(m => m.ConfirmPassword)

@Html.ValidationMessageFor(m => m.ConfirmPassword)

</div>

<div class="editor-label">

@Html.LabelFor(m => m.IsProfessional)

</div>

<div class="editor-field">

Yes @Html.RadioButtonFor(m => m.IsProfessional, true)

No @Html.RadioButtonFor(m => m.IsProfessional, false)

@Html.ValidationMessageFor(m => m.IsProfessional)

</div>

<div class="editor-label">

@Html.LabelFor(m => m.SelectedProfessionId)

</div>

<div class="editor-field">

@Html.DropDownListFor(m => m.SelectedProfessionId, (List<SelectListItem>) ViewBag.Professions)

@Html.ValidationMessageFor(m => m.SelectedProfessionId)

</div>

<div class="editor-label">

@Html.LabelFor(m => m.IsAdult)

</div>

<div class="editor-field">

@Html.CheckBoxFor(m => m.IsAdult)

@Html.ValidationMessageFor(m => m.IsAdult)

</div>

<p>

<input type="submit" value="Register" />

</p>

</fieldset>

</div>

}

The Action method for the load of the Register page is shown below:

public ActionResult Register()

{

     RegisterModel model = new RegisterModel { IsProfessional = false };

ViewBag.Professions = new List<SelectListItem>

{

new SelectListItem { Text = "None", Value = "-1" },

new SelectListItem { Text = "IT", Value = "IT" },

new SelectListItem { Text = "Accountancy", Value = "ACC" }

};

return View(model);

}

In ASP .NET MVC 4, you can create a bundle (in function RegisterBundles in BundleConfig.cs) for jFluent as shown below.

 bundles.Add(new ScriptBundle("~/bundles/jFluent").Include("~/Scripts/jFluent.js"));

You can add the bundle to your View as shown below (in .cshtml) :

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

@Scripts.Render("~/bundles/jFluent")

}

If you want a common single message for all rules on an input field then do the following:

 @Html.ValidationMessageFor(m => m.Email, "Common single error message here")

jFluent does single field validation on input Change event i.e. the input element that has changed is validated for all rules attached to it.

If you want to turn off validation on input Change event, you can specify an option:

 $.jFluentRules(RegisterRules, { validateOnChange: false });


Support blog:

I have setup a support blog where you can post requests for support.

http://jfluentvalidationplugin.blogspot.com.au/

Contribute:

If you want to contribute, the project is hosted on open source sites like:

GitHub:

https://github.com/VeritasSoftware/jFluent

Codeplex:

http://jfluent.codeplex.com

Also, you can add the plugin to your ASP .NET MVC project through the "Manage NuGet Packages" Visual Studio add-in.

NuGet:

https://nuget.org/packages/jFluent

Up Next
    Ebook Download
    View all
    Learn
    View all