Remove required validation using asp.net core

不羁的心 提交于 2019-12-05 20:14:11

Changing the required rule(s) on the client does not affect server side validation. Your [Required] attribute validation is still executed during the model binding process, therefore ModelState will be invalid, and you would manually need to check each property to determine if its invalid because of a [Required] attribute, or because of one of your other validation attributes.

In addition, you will need to add all the rules back again (or re-parse the $.validator) to get the client side validation for your normal submit.

Instead, include a bool property in your view model, so that you can use a conditional [RequiredIf] attribute (you could use a foolproof attribute, or the one in this project).

Your model would then include

public bool IsDraft { get; set; }
[RequiredIf("IsDraft", false, ErrorMessage = "...")]
public string FamilyName { get; set; }

and in the view

@Html.HiddenFor(m => m.IsDraft)

@Html.LabelFor(m => m.FamilyName)
@Html.TextBoxFor(m => m.FamilyName)
@Html.ValidationMessageFor(m => m.FamilyName)


<input id="Progress" type="button" value="Save Progress" class="btn btn-default" />
<input id="Final" type="button" value="Save Final" class="btn btn-default" />

and the associated scripts

$('#Progress').click(function() {
    $('#IsDraft').val('True');
    $(yourForm).submit();
});
$('#Final').click(function() {
    $('#IsDraft').val('False');
    $(yourForm).submit();
});

With your code you dispabled the client side validation. In order to make it work, you have two options. The first option is to remove the required from your model. The second is to remove the server side validation and write your own code in order to check the submited values.

// Remove this.
if (!ModelState.IsValid)
{
    return View(model);
}

You can make custom validation like this.

if (boolean expression)
{
    ModelState.AddModelError("Property", "Error message.");
    return View(model);
}

Replace the boolean expression with a check that you want to make, the Property with the property name which failed the validation and the Error message with the message that you want to display.

If you are using ASP, why not use an ASP Button?

<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return ValidationCheck();" />

Then the script is:

<script language="javascript" type="text/javascript">  
      function ValidationCheck() 
{
    var value = $("#TextBox1").val(); 

    if ((value === null) || (value == "")) 
        { 
          alert("Enter text!"); return false; 
        } 
    return true; } 
</script>

This way you can control the validation better.

An even better way would be to do validations on the server side with modal pop-ups etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!