简体   繁体   English

如何在ASP.NET Core 2.0中的自定义验证属性中进行客户端验证?

[英]How To Do Client-Side Validation In Custom Validation Attribute In ASP.NET Core 2.0?

Here I am trying to do both client and server side validation in Age property of model class contact for which i have used custom validation attribute ie Digt and UpperCase attribute for checking uppercase and digit in input, if not should give error message as specified in validation attribute. 在这里,我试图在模型类contact Age属性中进行客户端和服务器端验证,为此我使用了自定义验证属性(即DigtUpperCase属性)来检查输入中的大写和数字,如果不应该提供验证中指定的错误消息属性。
Now, the problem is that on click of submit button the validation message is displayed as required but before the click of submit button the error message is not displayed even though the condition for input is not meet. 现在的问题是,单击提交按钮时,将按要求显示验证消息,但是即使不满足输入条件,在单击提交按钮之前,也不会显示错误消息。

Any Help will be great and highly appreciated.Thank you 任何帮助将是巨大的,并高度赞赏。谢谢

Below is my both digit and uppercase custom validation attribute 以下是我的数字和大写自定义验证属性
Uppercase Attribute 大写属性

public class UpperCaseAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            string suppliedValue = (string)value;
            var hasUpperChar = new Regex(@"[A-Z]+");
            var match = hasUpperChar.IsMatch(suppliedValue);
            if (match == false)
            {
                return new ValidationResult("Input Should Have Uppercase ");
            }
        }
        return ValidationResult.Success;
    }
}



Digit Attribute 数字属性

public class DigitAttribute : ValidationAttribute
{ 
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            string suppliedValue = (string)value;
            var hasNumber = new Regex(@"[0-9]+");
            var match = hasNumber.IsMatch(suppliedValue);
            if(match == false)
            {
                return new ValidationResult("Input Should Have Number");
            }
        }
        return ValidationResult.Success;
    }
}


Below is my metadata for contact model class 以下是我的联系人模型类的元数据
ContactMetadata ContactMetadata

public class ContactMetadata
{
    public int Id { get; set; }
    [Required(ErrorMessage = "Age is Required")]
    [UpperCase]
    [Digit]
    public string Age { get; set; }
}



Below is my view Create View 下面是我的视图创建视图

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.0.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
<div class="row">
<div class="col-md-4">
    <form asp-action="Create">
        <div class="form-group">
            <label asp-for="Age" class="control-label"></label>
            <input asp-for="Age" class="form-control" />
            <span asp-validation-for="Age" class="text-danger"></span>
        </div>
        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </form>
</div>
</div>

Your validation attributes have to implement IClientModelValidator and you have to write your own validation logic on client-side as well: 您的验证属性必须实现IClientModelValidator,并且您还必须在客户端编写自己的验证逻辑:

public class UpperCaseAttribute: System.ComponentModel.DataAnnotations.ValidationAttribute, IClientModelValidator
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            string suppliedValue = (string)value;
            var hasUpperChar = new Regex(@"[A-Z]+");
            var match = hasUpperChar.IsMatch(suppliedValue);
            if (match == false)
            {
                return new ValidationResult("Input Should Have Uppercase ");
            }
        }
        return ValidationResult.Success;
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        AttributeUtils.MergeAttribute(context.Attributes, "data-val", "true");
        AttributeUtils.MergeAttribute(context.Attributes, "data-val-uppercase", FormatErrorMessage(context.ModelMetadata.GetDisplayName()));
    }
}

public class AttributeUtils
{
    public static bool MergeAttribute(
        IDictionary<string, string> attributes,
        string key,
        string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }
        attributes.Add(key, value);
        return true;
    }
}

You have to include jquery.validate.min.js and jquery.validate.unobtrusive.min.js in html. 您必须在html中包含jquery.validate.min.js和jquery.validate.unobtrusive.min.js。 Then add the corresponding rules and functions after the content is loaded as follows: 然后,在加载内容后,添加相应的规则和功能,如下所示:

$.validator.addMethod("uppercase",
    function (value, element, params) {
        return value === value.toUpperCase();
    });

$.validator.unobtrusive.adapters.add("uppercase",
    params,
    function (options) {
        options.rules[index] = options.params;
        options.messages[index] = options.message;
    });

When you create a custom validation attribute for server side, you need to write your own custom validation script for client side as well. 为服务器端创建自定义验证属性时,还需要为客户端编写自己的自定义验证脚本。 In asp.net mvc, the client side validation was to be hooked with the unobtrusive validation scripts. 在asp.net mvc中,客户端验证将与不引人注目的验证脚本挂钩。 For .NET Core, you can refer this Defining client validation rules on the client side 对于.NET Core,可以在客户端参考此“ 定义客户端验证规则”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET MVC客户端验证的自定义属性 - ASP.NET MVC client-side validation of custom attribute 自定义客户端验证未在 ASP.NET 内核中触发 - Custom Client-Side Validation not triggering in ASP.NET Core ASP.Net Core MVC - 自定义属性的客户端验证 - ASP.Net Core MVC - Client-side validation for custom attribute 自定义验证属性中的客户端验证 - asp.net mvc 4 - client-side validation in custom validation attribute - asp.net mvc 4 ASP.NET MVC3 - 自定义验证属性 - &gt;客户端损坏 - ASP.NET MVC3 - Custom validation attribute -> Client-side broken 如何在 ASP.NET Core 3.1 MVC 中进行RequiredIf 客户端和服务器端验证? - How to make RequiredIf Client-side and server-side validation in ASP.NET Core 3.1 MVC? ASP.NET razor 页面上的自定义验证属性的核心客户端验证 - ASP.NET Core client side validation for custom validation attribute on razor page 如何使用 ASP.NET Core 更改输入字段的客户端验证错误 CSS 类? - How to alter the client-side validation error CSS class of an input field using ASP.NET Core? ASP.Net Core 客户端验证:是否存在“验证成功”的 DOM 事件? - ASP.Net Core client-side validation: is there a “validation succeeded” DOM event? 用于客户端和服务器端验证的 ASP.NET Core 重用代码 - ASP.NET Core Reuse Code for Client-Side and Server-Side Validation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM