programing tip

ASP .NET MVC 필드 별 수준에서 클라이언트 쪽 유효성 검사 사용 안 함

itbloger 2020. 11. 3. 07:43
반응형

ASP .NET MVC 필드 별 수준에서 클라이언트 쪽 유효성 검사 사용 안 함


데이터 주석 및 jQuery 유효성 검사 플러그인과 함께 ASP .NET MVC 3을 사용하고 있습니다.

특정 필드 (또는 특정 데이터 주석)가 서버 측에서만 검증되어야 함을 표시하는 방법이 있습니까?

마스킹 플러그인이있는 전화 번호 필드가 있고 정규식 유효성 검사기가 사용자 쪽에서 미쳐 버립니다. 정규식은 (누군가 자바 스크립트 유효성 검사를 해킹하기로 결정한 경우) 안전 장치 일뿐이므로 클라이언트 측에서 실행할 필요가 없습니다. 그러나 나는 여전히 다른 유효성 검사가 클라이언트 측을 실행하고 싶습니다.


이 솔루션이 MVC3에서 작동하는지 확실하지 않습니다. MVC4에서 확실히 작동합니다.

필드를 렌더링하기 전에 Razor보기에서 클라이언트 측 유효성 검사를 비활성화하고 필드가 렌더링 된 후 클라이언트 측 유효성 검사를 다시 활성화 할 수 있습니다.

예:

<div class="editor-field">
    @{ Html.EnableClientValidation(false); }
    @Html.TextBoxFor(m => m.BatchId, new { @class = "k-textbox" })
    @{ Html.EnableClientValidation(true); }
</div>

여기서는 BatchId 필드에 대한 클라이언트 측 유효성 검사를 비활성화합니다.

또한 이것에 대한 약간의 도우미를 개발했습니다.

public static class YnnovaHtmlHelper
{
    public static ClientSideValidationDisabler BeginDisableClientSideValidation(this HtmlHelper html)
    {
        return new ClientSideValidationDisabler(html);
    }
}

public class ClientSideValidationDisabler : IDisposable
{
    private HtmlHelper _html;

    public ClientSideValidationDisabler(HtmlHelper html)
    {
        _html = html;
        _html.EnableClientValidation(false);
    }

    public void Dispose()
    {
        _html.EnableClientValidation(true);
        _html = null;
    }
}

다음과 같이 사용합니다.

<div class="editor-field">
    @using (Html.BeginDisableClientSideValidation()) {
        @Html.TextBoxFor(m => m.BatchId, new { @class = "k-textbox" })
    }
</div>

누구든지 더 나은 솔루션이 있으면 알려주십시오!

이 도움을 바랍니다.


다음과 같이 data-val='false'속성 을 추가하여 단일 필드에 대한 클라이언트 측 방해없는 유효성 검사를 끌 수 있습니다 .

@Html.TextBoxFor(m => m.BatchId, new { data_val = "false" })

이것은 data-val='true'MVC가 System.ComponentModel.DataAnnotations속성 으로 인해 추가 하는 속성을 재정의 합니다. HTML 요소는 여전히 다른 유효성 검사 속성 (예 : data-val-required)으로 장식되지만 효과가 없습니다.

( 밑줄 주 에서 data_val위. MVC가 자동으로 익명 형식 속성에서 하이픈에 밑줄을 변환, 그렇게 data_valdata-valHTML을 렌더링 할 때)


MVC5는 jquery.validate를 사용합니다.

http://jqueryvalidation.org/rules/

If you want to remove validations in MVC5 client-Side you need to do the following:

Remove all validations on 'myinput'

$("#myinput").rules("remove");

Specific validations

$("#myinput").rules("remove", "min max" );

Listing the validations can help

$("#myinput").rules();

Then you will need to correct your Code Behind to validate manually your model or differently because ModelState.IsValid will be false. Using ModelState.Clear() and TryValidateModel can then be handy.

Edit:

Disabling the control also remove the validations.

$("#myinput").attr('disabled', disabledValue);

Assuming you use default unobtrusive validation, You could use some javascript to remove rules on client side. Take a look at Plugins/Validation/rules


To achieve this goal in the given scenario, we need to make two tweaks.

Client Side

To disable client side validation, we need to disable it by force.

@Html.EditorFor(model => model.Password, new { htmlAttributes = new {  @data_val = "false" , @class = "form-control"} })

Notice the @data_val= “false”. It will disable the validation on this field.

Server Side (In Action)

When the model is validated on the post action, ModelState.IsValid will always return false because password is not provided. Here we have to provide the current password to the model and Re-validate the model.

var userObj = db.Users_Info.Where(a => a.Id == users_Info.Id).FirstOrDefault();
if (String.IsNullOrEmpty(users_Info.Password))
{
  users_Info.Password = userObj.Password;
}
ModelState.Clear();
TryValidateModel(users_Info);

Let me explain, first we retrieve current information saved in the database which we are using later to assign to current model if password is not provided. The last two lines actually reset the ModelState to return updated result on ModelState.IsValid.


I ran into trouble with data_val="true". I had a sequence of radio buttons tied to a single property in my model. The data validation only worked when I applied data_val="true" to the first @Html.RadioButtonFor call.

In debugging this, I discovered you can also disable or alter individual rules on the client side by using data_rule_??. The rules can be found in the jquery validation documentation.

for example;

@Html.RadioButtonFor(m => m.Answer, "Yes", new { data_rule_Required = "false" });
@Html.TextBoxFor(m => m.Answer, new { data_rule_minlength = "10" }

If you want to remove validations in MVC5 client-Side you need to do the following:

$("#Email").rules("remove", {
                        "required",
                        "minlength",
                        "email"                           
                        }
                    });

참고URL : https://stackoverflow.com/questions/5630424/asp-net-mvc-disable-client-side-validation-at-per-field-level

반응형