使用远程验证多个字段验证 [英] Multiple fields validation using Remote Validation
问题描述
我有以下型号:
public class Customer
{
public string FirstName {get;set;}
public string LastName {get; set;}
[Remote("CardExisting", "Validation", AdditionalFields="FirstName,LastName")
public string CardNumber {get; set;}
}
CardExisting行动将检查是否有对cardNumber为名字和姓氏的结合现有记录。
CardExisting action will check that there is an existing record for the combination of cardNumber for the firstName and LastName.
如果用户首先会输入卡号,然后他的名字,我不能确认他,所以当他返回和输入他的名字,我需要远程再次验证,我该怎么做,当焦点已经从cardnumber遗失的财物?
What if user will first enter the card number and then his name, I cant validate him, so when he returns and input his name I need to remote validate again, how can I do that when focus was already lost from cardnumber property?
推荐答案
拓展上Jaluka的回答,我写了认定,都有每个远程验证元素这个辅助方法附加字段,然后导致验证上所述元件火每个时间这些领域的变化之一。
Expanding on Jaluka's answer, I wrote this helper method that finds each remotely validating element that has "additional fields," and then causes validation on said element to fire each time one of those fields changes.
// I hate naming things
function initializeRemotelyValidatingElementsWithAdditionalFields($form) {
var remotelyValidatingElements = $form.find("[data-val-remote]");
$.each(remotelyValidatingElements, function (i, element) {
var $element = $(element);
var additionalFields = $element.attr("data-val-remote-additionalfields");
if (additionalFields.length == 0) return;
var rawFieldNames = additionalFields.split(",");
var fieldNames = $.map(rawFieldNames, function (fieldName) { return fieldName.replace("*.", ""); });
$.each(fieldNames, function (i, fieldName) {
$form.find("#" + fieldName).change(function () {
// force re-validation to occur
$element.removeData("previousValue");
$element.valid();
});
});
});
}
调用函数像这样:
Call the function like so:
$(document).ready(function() {
initializeRemotelyValidatingElementsWithAdditionalFields($("#myFormId"));
});
这篇关于使用远程验证多个字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!