[英]How to remove 'required' setting from form field using jQuery unobtrusive validation
I am having some trouble removing 'required' field validation from a field on a form that is using jQuery validation and jQuery unobtrusive. 我在从使用jQuery验证和jQuery不引人注目的表单上的字段中删除“必需”字段验证时遇到了一些麻烦。
I have the following razor view - 我有以下剃刀视图-
<div class="form-group @Html.Raw(Html.HasError(x => x.TargetNumber) ? "has-error" : null)">
<div class="col-md-12">
<p><strong>How much will you raise</strong></p>
</div>
<div class="col-sm-6">
@Html.TextBoxFor(x => x.TargetNumber, new { id = "TargetNumber", @class = "form-control", placeholder = "Target", type = "number", Value="Target" })
@Html.ValidationMessageFor(x => x.TargetNumber, null, new { @class = "error" })
</div>
</div>
and view model 和查看模型
[Required(ErrorMessage = "Please enter a valid value.")]
[Range(100, Double.PositiveInfinity, ErrorMessage = "The minimum amount for this event is £100")]
public double TargetNumber { get; set; }
I have tried the following to make the field non required - 我尝试了以下操作以使该字段为非必填字段-
Yet, still the field is flagged as required on submit. 但是,仍然将该字段标记为提交时需要。
Can anyone please suggest a way that I can make this field non required. 任何人都可以提出一种我可以使此字段为非必填项的建议。
Thanks, 谢谢,
For structs, the RequiredAttribute
only changes the error message, the properties are always required. 对于结构, RequiredAttribute
仅更改错误消息,始终需要属性。
If you don't want them to be required, you need to make them nullable: 如果您不希望使用它们,则需要将它们设置为可为空:
[Range(100, Double.PositiveInfinity, ErrorMessage = "The minimum amount for this event is £100")]
public double? TargetNumber { get; set; }
You have to set up a rule for your property using jQuery like so: 您必须像这样使用jQuery为您的媒体资源设置规则:
$('#myForm').validate({
rules: {
TargetNumber: {
required: function (element) {
return false;
}
}
}
});
TargetNumber should be the name attribute and not the id attribute. TargetNumber应该是name属性,而不是id属性。 I think for MVC it automatically assigns the name attribute based on the model name, but check in your developer tools to see what value is being assigned to the name attribute. 我认为对于MVC,它会根据模型名称自动分配name属性,但是请检查开发人员工具以查看为name属性分配了什么值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.