使用 jQuery 验证来验证自定义方法
validate custom method with jQuery validation
我想验证我的表单,这样如果列表中已经存在代码,我就无法在下面的输入中输入代码。
<input id="form:inptCode" type="text" name="form:inptCode" class="number">
下面是 primefaces orderlist 元素的 html。
<select id="form:choices_values" name="form:choices_values" multiple="true" class="ui-helper-hidden">
<option value="1" selected="selected">1</option>
</select>
因此,列表包含值 1。如果我在 inputText 中键入数字 1,应该会出现错误消息。
为了实现这一点,我添加了一个方法,并尝试在该方法 returns 为 false 时验证表单。
我没有太多使用 jQuery 验证的经验,实际上我只写了几个方法。
$.validator.addMethod('codExistss', function (value, element) {
var lstChoices = document.getElementById('form:choices_values');
for (i = 0; i < lstChoices.options.length; i++) {
return value === lstChoices.option[i].value;
}
}, "The code already exists.");
$(document).ready(function () {
$('#form').validate({
rules: {
'form:inptCode': {
codExistss: false
}
}
});
});
看来我的代码不起作用。那么,你能帮我理解为什么吗?
你有一个遍历所有列表选项的循环:
for (i = 0; i < lstChoices.options.length; i++) {
return value === lstChoices.option[i].value;
}
假设您有超过 1 个选项,条件只有 1 次 return 为真并且您的验证被破坏就足够了。
第二件事是您没有为自定义函数打开规则标志:
你有 codExistss: false
这意味着 "don't validate the input by this rule",将其更改为 true。
试试这个:
$.validator.addMethod('codExistss', function (value, element) {
var lstChoices = document.getElementById('form:choices_values');
if(lstChoices.options[lstChoices.selectedIndex].value===value) {return false;}
return true;
},"The code already exists.");
$(document).ready(function () {
$('#form').validate({
rules: {
'form:inptCode': {
// Specify that form:inptCodeshould be validated
// by codExistss rule
codExistss: true
}
}
});
});
如果我可以拯救任何人的痛苦时刻,我希望这对您有所帮助!
我想要一个必需的 if,但仅适用于单一方法:创建,但不一定适用于编辑。自定义验证。
我的模型属性是这样的:
/// <summary>
/// The HttpPostedFileBase for Uploading Images.
/// </summary>
[NotMapped]
[Display(Name = "Image")]
[RequiredIf("Create", ErrorMessage = "The Image field is required.")]
public HttpPostedFileBase DisplayImage { get; set; }
这是自定义 RequiredIf 属性 class:
/// <summary>
/// A Custom Required If Attribute
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class RequiredIfAttribute : ValidationAttribute
{
#region Fields:
#endregion
#region Properties:
private string Action { get; set; }
#endregion
public RequiredIfAttribute(object action)
{
Action = action.ToString();
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string action = HttpContext.Current.Request.RequestContext.RouteData.Values["action"].ToString();
// If Action == Create and the Image is NOT Null:
if ((Action.Equals(action)) && (value != null))
return ValidationResult.Success;
else
// If Action == Edit and Image is Null:
if((!Action.Equals(action)) && (value == null))
return ValidationResult.Success;
else
// Return Error Message:
return new ValidationResult(ErrorMessage);
}
}
我使用了服务器端验证,因此不需要 Javascript/JQuery,为简单起见。
这是我的控制器的一个片段:
/// <summary>
/// POST: /Create
/// To protect from overposting attacks, please enable the specific properties you want to bind to, for
/// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
/// </summary>
/// <param name="myModelViewModels"></param>
/// <returns></returns>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "My Binding Attributes")] MyModelViewModels myModelViewModels)
{
// If the Validation has failed, then the Model State will be Invalid!
if (ModelState.IsValid)
{
// Do all the funky coding in here...
}
// Return the InValid Model here:
return View(MyModelViewModels);
}
这有点两步,模型必须 return 在客户知道要求已经满足或尚未满足之前提供给客户! JQuery 很适合用于客户端验证!
我想验证我的表单,这样如果列表中已经存在代码,我就无法在下面的输入中输入代码。
<input id="form:inptCode" type="text" name="form:inptCode" class="number">
下面是 primefaces orderlist 元素的 html。
<select id="form:choices_values" name="form:choices_values" multiple="true" class="ui-helper-hidden">
<option value="1" selected="selected">1</option>
</select>
因此,列表包含值 1。如果我在 inputText 中键入数字 1,应该会出现错误消息。
为了实现这一点,我添加了一个方法,并尝试在该方法 returns 为 false 时验证表单。 我没有太多使用 jQuery 验证的经验,实际上我只写了几个方法。
$.validator.addMethod('codExistss', function (value, element) {
var lstChoices = document.getElementById('form:choices_values');
for (i = 0; i < lstChoices.options.length; i++) {
return value === lstChoices.option[i].value;
}
}, "The code already exists.");
$(document).ready(function () {
$('#form').validate({
rules: {
'form:inptCode': {
codExistss: false
}
}
});
});
看来我的代码不起作用。那么,你能帮我理解为什么吗?
你有一个遍历所有列表选项的循环:
for (i = 0; i < lstChoices.options.length; i++) {
return value === lstChoices.option[i].value;
}
假设您有超过 1 个选项,条件只有 1 次 return 为真并且您的验证被破坏就足够了。
第二件事是您没有为自定义函数打开规则标志:
你有 codExistss: false
这意味着 "don't validate the input by this rule",将其更改为 true。
试试这个:
$.validator.addMethod('codExistss', function (value, element) {
var lstChoices = document.getElementById('form:choices_values');
if(lstChoices.options[lstChoices.selectedIndex].value===value) {return false;}
return true;
},"The code already exists.");
$(document).ready(function () {
$('#form').validate({
rules: {
'form:inptCode': {
// Specify that form:inptCodeshould be validated
// by codExistss rule
codExistss: true
}
}
});
});
如果我可以拯救任何人的痛苦时刻,我希望这对您有所帮助!
我想要一个必需的 if,但仅适用于单一方法:创建,但不一定适用于编辑。自定义验证。
我的模型属性是这样的:
/// <summary>
/// The HttpPostedFileBase for Uploading Images.
/// </summary>
[NotMapped]
[Display(Name = "Image")]
[RequiredIf("Create", ErrorMessage = "The Image field is required.")]
public HttpPostedFileBase DisplayImage { get; set; }
这是自定义 RequiredIf 属性 class:
/// <summary>
/// A Custom Required If Attribute
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class RequiredIfAttribute : ValidationAttribute
{
#region Fields:
#endregion
#region Properties:
private string Action { get; set; }
#endregion
public RequiredIfAttribute(object action)
{
Action = action.ToString();
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string action = HttpContext.Current.Request.RequestContext.RouteData.Values["action"].ToString();
// If Action == Create and the Image is NOT Null:
if ((Action.Equals(action)) && (value != null))
return ValidationResult.Success;
else
// If Action == Edit and Image is Null:
if((!Action.Equals(action)) && (value == null))
return ValidationResult.Success;
else
// Return Error Message:
return new ValidationResult(ErrorMessage);
}
}
我使用了服务器端验证,因此不需要 Javascript/JQuery,为简单起见。
这是我的控制器的一个片段:
/// <summary>
/// POST: /Create
/// To protect from overposting attacks, please enable the specific properties you want to bind to, for
/// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
/// </summary>
/// <param name="myModelViewModels"></param>
/// <returns></returns>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "My Binding Attributes")] MyModelViewModels myModelViewModels)
{
// If the Validation has failed, then the Model State will be Invalid!
if (ModelState.IsValid)
{
// Do all the funky coding in here...
}
// Return the InValid Model here:
return View(MyModelViewModels);
}
这有点两步,模型必须 return 在客户知道要求已经满足或尚未满足之前提供给客户! JQuery 很适合用于客户端验证!