http://posabsolute.github.io/jQuery-Validation-Engine/
Eg.
https://www.awesomes.cn/repo/posabsolute/jquery-validation-engine
First include jQuery on your page
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"
type="text/
javascript"></script>
Include jquery.validationEngine
and its locale
<script
src="js/jquery.validationEngine-en.js" type="text/javascript"
charset="utf-8"></script>
<script src="js/jquery.validationEngine.js"
type="text/javascript" charset="utf-8"></script>
Finally include the desired theme
<link rel="stylesheet"
href="css/validationEngine.jquery.css" type="text/css"/>
Eg.
<input value="http://" class="validate[required,custom[url]] text-input" type="text" name="url" id="url"
data-prompt-position="topLeft:70" />
<input value="" class="validate[required] text-input" type="text" name="req" id="req"
data-prompt-position="bottomLeft:20,5" />
<input value="too many spaces obviously" class="validate[required,custom[onlyLetterNumber]]" type="text"
name="special" id="special" data-prompt-position="bottomRight:-100,3" />
In jquery.validationengine-en.js
, add the following function
"ajaxCheckUserNameAlreadyExist": {
"url": "CheckUserNameAlreadyExist",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
"extraDataDynamic": ['#UserName', '#FirstName', '#EmployeeGroupID'],
"alertText": "*
This user is already taken",
"alertTextLoad": "*
Validating, please wait",
"alertTextOk": "*
This username is available"
},
@using (Html.BeginForm("CreateNew", "Users", FormMethod.Post, new { @id =
"frmUser" }))
{
@Html.AntiForgeryToken()
@Html.Hidden("EmployeeGroupID", "12345")
. .
. . . . . . . . .. .
<div class="form-group">
@Html.LabelFor(model
=> model.UserName, htmlAttributes: new {
@class = "control-label
col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model
=> model.UserName, new { htmlAttributes = new { @class = "form-control validate[required,
ajax[ajaxCheckUserNameAlreadyExist]]" } })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model =>
model.DepartmentID, "DepartmentID", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("DepartmentID", (IEnumerable<SelectListItem>)ViewBag.DepartmentID, "--Select Department--", htmlAttributes: new { @class = "form-control validate[required]" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2
col-md-10">
<input type="submit" value="Create" class="btn
btn-default btnSubmit" />
</div>
</div>
. . . . .. . . . .. . . . .
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery.validationEngine-en.js"></script>
<script src="~/Scripts/jquery.validationEngine.js"></script>
<script type="text/javascript">
$(function () {
$('#frmUser').validationEngine('attach', {
promptPosition: "topRight", showArrow: true,
//means that the
form will always submit in ajax , if set to true, the form data is sent/submit
asynchronously via ajax to the form.action url (get)
//if it is false, the onAjaxFormComplete:
ajaxValidationCallback will not fire,
//instead onValidationComplete function will fire.
ajaxFormValidation: false,
ajaxFormValidationMethod: 'post',
//Do something when the request comes
back
// Ajax form validation callback method: boolean
onComplete(form, status, errors, options)
// retuns false if the form.submit event needs to be
canceled.
onAjaxFormComplete:
ajaxValidationCallback,
//Do something before the submit ajax validation
onBeforeAjaxFormValidation: beforeCall,
onValidationComplete: function (form, status) {
if (status == true) {
console.log("The onValidationComplete status
is true");
var theurl = $("#frmUser").attr('action');
$.ajax({
url: theurl,
type: 'post',
dataType: 'json',
data: $("#frmUser").serialize(),
success: function (data) {
console.log("Text= " + data.Text);
console.log("Message= " + data.Message);
if (data.Text == "OK") {
window.location.href = "/Users/Index";
}
else {
window.location.href = "/Home/About";
}
},
error: function () {
console.log("There is some error!");
window.location.href = "/Users/SomeError";
}
}); //ajax req end
} // status == true end
} // onValidationComplete end
}); // validationEngine declaration end
}); // document ready
end
function beforeCall(form, options) {
if
(window.console)
console.log("Right before the AJAX form
validation call");
return true;
}
// Called once the server replies to
the ajax form validation request
// If
ajaxFormValidation is set to "false", then ajaxValidationCallback
will not fire
function ajaxValidationCallback(status, form, json, options) {
console.log("ajaxValidationCallback
called");
if (status
=== true) {
console.log("the form is valid!");
return false;
}
}
</script>
}
public JsonResult CheckUserNameAlreadyExist(string name,string UserName,string FirstName,string EmployeeGroupID)
{
bool? flag =
false;
ArrayList returnValues = new ArrayList();
if
(UserName == "test")
{
flag = false;
// return false; //new JsonResult({"UserName",
false, "Already exists" })l;
}
else
{
flag = true;
// return true; //Json(new { msg = "ok" },
JsonRequestBehavior.AllowGet);
}
if (flag
== false)
{
returnValues.Add("UserName");
returnValues.Add(false);
returnValues.Add("UserName already exists.");
}
else {
returnValues.Add("UserName");
returnValues.Add(true);
returnValues.Add("UserName available!");
}
return Json(returnValues,JsonRequestBehavior.AllowGet);
}
public ActionResult CreateNew()
{
ViewBag.DepartmentID = new SelectList(db.Department, "ID", "Name");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateNew([Bind(Include = "FirstName,LastName,UserName,Password,ConfirmPassword,EmailID,DepartmentID")] User user)
{
//if (user.FirstName != null) {
// //throw new
HttpException(404, "FirstName is not null");
// return new
HttpStatusCodeResult(404, "FirstName is not found");
//}
if
(ModelState.IsValid)
{
db.User.Add(user);
db.SaveChanges();
var msg = new { Text = "OK",
Message = "DONE" };
return Json(msg, JsonRequestBehavior.AllowGet);
}
else {
return Json(new { Text="NOTOK", Message="FAIL"}, JsonRequestBehavior.AllowGet);
}
}
General Note:
ajaxFormValidation
If set to true, turns Ajax form validation logic on. defaults to *false*.
form validation takes place when the validate() action is called or when the form is submitted.
onBeforeAjaxFormValidation(form, options)
When ajaxFormValidation is turned on, function called before the asynchronous AJAX form validation call. May return false to stop the Ajax form validation
onAjaxFormComplete: function(form, status, errors, options)
When ajaxFormValidation is turned on, function is used to asynchronously process the result of the validation.
inlineAjax: false,
// if set to true, the form data is sent asynchronously via ajax to the form.action url (get)
ajaxFormValidation: false,
// The url to send the submit ajax validation (default to action)
ajaxFormValidationURL: false,
// HTTP method used for ajax validation
ajaxFormValidationMethod: 'get',
// Ajax form validation callback method: boolean onComplete(form, status, errors, options)
// retuns false if the form.submit event needs to be canceled.
onAjaxFormComplete: $.noop,
// called right before the ajax call, may return false to cancel
onBeforeAjaxFormValidation: $.noop,
// Stops form from submitting and execute function associated with it
onValidationComplete: false,
If set to true, turns Ajax form validation logic on. defaults to *false*.
form validation takes place when the validate() action is called or when the form is submitted.
onBeforeAjaxFormValidation(form, options)
When ajaxFormValidation is turned on, function called before the asynchronous AJAX form validation call. May return false to stop the Ajax form validation
onAjaxFormComplete: function(form, status, errors, options)
When ajaxFormValidation is turned on, function is used to asynchronously process the result of the validation.
inlineAjax: false,
// if set to true, the form data is sent asynchronously via ajax to the form.action url (get)
ajaxFormValidation: false,
// The url to send the submit ajax validation (default to action)
ajaxFormValidationURL: false,
// HTTP method used for ajax validation
ajaxFormValidationMethod: 'get',
// Ajax form validation callback method: boolean onComplete(form, status, errors, options)
// retuns false if the form.submit event needs to be canceled.
onAjaxFormComplete: $.noop,
// called right before the ajax call, may return false to cancel
onBeforeAjaxFormValidation: $.noop,
// Stops form from submitting and execute function associated with it
onValidationComplete: false,
$(function() {
//hang on event of form with id=myform
$("#myform").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
//do your own request an handle the results
$.ajax({
url: actionurl,
type: 'post',
dataType: 'json',
data: $("#myform").serialize(),
success: function(data) {
... do something with the data...
}
});
});
});
//hang on event of form with id=myform
$("#myform").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
//do your own request an handle the results
$.ajax({
url: actionurl,
type: 'post',
dataType: 'json',
data: $("#myform").serialize(),
success: function(data) {
... do something with the data...
}
});
});
});
The below line is to check that the form is valid or not
$("#formid").validationEngine('validate');
The engine will automatically validate the form while submitting,
the '('validate')' is used if you want to directly validate the form without submitting it.
jQuery("#approvalForm").validationEngine('attach', {
onValidationComplete: function(form, status){
if (status == true) {
$('#progress').show();
$('#approvalForm').trigger('submit');
}else{
$('#progress').hide();
}
}
$("#formid").validationEngine('validate');
The engine will automatically validate the form while submitting,
the '('validate')' is used if you want to directly validate the form without submitting it.
jQuery("#approvalForm").validationEngine('attach', {
onValidationComplete: function(form, status){
if (status == true) {
$('#progress').show();
$('#approvalForm').trigger('submit');
}else{
$('#progress').hide();
}
}
// TO DISABLE VALIDATION FOR SPECIFIC SUBMIT BUTTONS
$(function () {
$('[id*=btnSubmit]').bind("click", function () {
$("#form1").validationEngine('attach', { promptPosition: "topRight" });
});
$('[id*=btnCancel]').bind("click", function () {
$("#form1").validationEngine('detach');
});
});
$(function () {
$('[id*=btnSubmit]').bind("click", function () {
$("#form1").validationEngine('attach', { promptPosition: "topRight" });
});
$('[id*=btnCancel]').bind("click", function () {
$("#form1").validationEngine('detach');
});
});
If a function is assigned to onValidationComplete then this is executed instead of the form being submitted.
Until jQuery-Validation-Engine version 2.6.4 this was the only behavior, from this version on you can return true in onValidationComplete to tell the validation engine to continue submitting the form. The default behavior if the function has no return value is still to stop the submit.
onValidationComplete
When defined, stops the the form from auto-submitting, and lets you handle the validation status via a function
jQuery("#formID2").validationEngine('attach', {
onValidationComplete: function(form, status){
alert("The form status is: " +status+", it will never submit");
}
});
0 comments:
Post a Comment