从表单提交的输入字段中删除所需的属性

问题描述 投票:0回答:9

型号:

[Display(Name = "City"]
[Required]
[RegularExpression(@"^(?!\d$).*$"]
[StringLength(20,MinimumLength = 2]
public string City { get; set; }

形式:

@Html.LabelFor(x => x.City, new { @class = "control-label" })
@Html.TextBoxFor(x => x.City, new {id="city" })

脚本:

<script>
  $(document).ready(function () {   
    $("#identificationForm").submit(function (e) {
      var required=document.getElementById("city").required;
      console.log(required);
      // e.preventDefault();
     });
  });
</script>

如果满足某些条件,我想删除所需的属性。无法以这种方式执行此操作。我该如何实现?

javascript jquery html asp.net-mvc-4
9个回答
54
投票

JavaScript 区分大小写。

使用

document.getElementById("city").required = false;

示范

请注意,当您尝试在元素存在之前访问该元素时,您的代码将无法正常工作。如果您不在事件上执行代码,请将脚本放在元素之后:

<input type="text" id="city" required>
<script>
if(somecondition is true){
    document.getElementById("city").required = false;
}
</script>

还请注意,您不能在提交函数中更改它并期望您的表单被提交,因为为时已晚:如果未填写必填字段,则不会调用此事件处理程序!


15
投票

您可以使用:

document.getElementById("city").removeAttribute("required");

或使用 jQuery

$('#city').removeAttr('required')

5
投票

你应该这样做:

if(somecondition is true)
{
  var city = document.getElementById("city");
  city.removeAttribute('required');
}

1
投票

On Submit
函数删除所需的属性时,表单已经通过了验证。这些步骤首先是您必须禁用验证,然后您才能提交必填字段为空的表单。接下来删除所需的属性,最后通过
$.validator.unubtrusive.parse(form)
手动调用验证,这将通过调用其他验证类型(例如
string length
formatting
)来验证表单,除了必需的属性之外的所有其他内容。检查
if form.valid() then submit() else
什么都不做。


1
投票

在 php 中非常简单,这不会在提交时验证您的表单,

<input type="submit" onclick="return confirm('Are you sure?')" value="Abort Test" formnovalidate>

0
投票

不确定是否有人想出更好的方法来做到这一点,它可能不是最有效的方法,但你可以使用 PHP 来完成它。如果您希望满足的条件在页面加载之前已知,那么您可以这样做:

<input type="text" id="city" 

<?php
     if (condition_is_met) {
          echo ">";
     } else {
          echo "required>";
     }
?>

0
投票

如果您将文本字段放在表单中,则可以使用名为 novalidate 的特殊属性覆盖必填字段。这是语法:

<form novalidate> .. </form>

举个例子:

<form novalidate>
  Zip code: <input type="text" name="zipcode" pattern="[0-9]{5}" required><br/>

  <input type="submit">
</form>

novalidate 属性这是一个链接,其中包含两个使用 novalidate 属性的现场演示。


0
投票

或者在提交表单的那一刻,如果它为空,您可以将其禁用:

if($("#City").val().trim().length == 0)
    $("#City").attr("disabled", true);


0
投票

这适用于我的数据注释。使用“规则”功能。

$("#FileUpload").rules("remove", "required");

并添加:

$("#FileUpload").rules("add", "required");

更新:这将修复前端验证,但后端验证仍然失败。为了使 ModelState 有效,我更改了该输入的 ValidationState。

ModelState["FileUpload"].ValidationState = Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Valid;

我确实检查以确保这也是唯一的错误:

if (ModelState["FileUpload"].Errors.Count == 1)
    if (ModelState["FileUpload"].Errors[0].ErrorMessage.Equals("The FileUpload field is required."))
        ModelState["FileUpload"].ValidationState = Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Valid;
© www.soinside.com 2019 - 2024. All rights reserved.