int数据类型的服务器端验证 [英] Server side validation of int datatype

查看:124
本文介绍了int数据类型的服务器端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了定义Validator属性

I made custom Validator attribute

partial class DataTypeInt : ValidationAttribute
{
    public DataTypeInt(string resourceName)
    {
        base.ErrorMessageResourceType = typeof(blueddPES.Resources.PES.Resource);
        base.ErrorMessageResourceName = resourceName;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        string number = value.ToString().Trim();
        int val;
        bool result = int.TryParse(number,out val );
        if (result)
        {
            return ValidationResult.Success;
        }
        else 
        {
            return new ValidationResult("");
        }
    }
}

但是,当我的文本框,然后价值== NULL 键,当我进入int值则价值==输入值输入的字符串,而不是int值; 。为什么呢?

But when entered string instead of int value in my textbox then value==null and when i entered int value then value==entered value;. Why?

有没有用,我可以达到同样的(确保在服务器端只)

Is there any alternate by which i can achieve the same (make sure at server side only)

推荐答案

之所以出现这种情况是因为该模型粘合剂(它运行的之前任何验证)是无法绑定无效值为整数。这就是为什么你的验证器里面你没有得到任何价值。如果您希望能够验证这一点,你可以写整数类型的自定义模型粘合剂。

The reason this happens is because the model binder (which runs before any validators) is unable to bind an invalid value to integer. That's why inside your validator you don't get any value. If you want to be able to validate this you could write a custom model binder for the integer type.

下面的这种模型绑定如何看起来像:

Here's how such model binder could look like:

public class IntegerBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        int temp;
        if (value == null || 
            string.IsNullOrEmpty(value.AttemptedValue) || 
            !int.TryParse(value.AttemptedValue, out temp)
        )
        {
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, "invalid integer");
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
            return null;
        }

        return temp;
    }
}

,你会在的Application_Start 注册它:

ModelBinders.Binders.Add(typeof(int), new IntegerBinder());

但你可能会问:如果我想自定义错误消息?毕竟,这就是我试图在首位来实现。什么是写这个模型绑定点时,默认的已经这样做对我来说,这只是我无法自定义错误信息?

But you might ask: what if I wanted to customize the error message? After all, that's what I was trying to achieve in the first place. What's the point of writing this model binder when the default one already does that for me, it's just that I am unable to customize the error message?

嗯,这是pretty容易。你可以创建一个将被用来装饰你的看法模型和其中将包含错误信息的自定义属性和模型绑定内你就可以获取此错误信息,并用它来代替。

Well, that's pretty easy. You could create a custom attribute which will be used to decorate your view model with and which will contain the error message and inside the model binder you will be able to fetch this error message and use it instead.

所以,你可以有一个虚拟的验证属性:

So, you could have a dummy validator attribute:

public class MustBeAValidInteger : ValidationAttribute, IMetadataAware
{
    public override bool IsValid(object value)
    {
        return true;
    }

    public void OnMetadataCreated(ModelMetadata metadata)
    {
        metadata.AdditionalValues["errorMessage"] = ErrorMessage;
    }
}

,你可以用它来装饰你的视图模型:

that you could use to decorate your view model:

[MustBeAValidInteger(ErrorMessage = "The value {0} is not a valid quantity")]
public int Quantity { get; set; }

和适应模型绑定:

public class IntegerBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        int temp;
        var attemptedValue = value != null ? value.AttemptedValue : string.Empty;

        if (!int.TryParse(attemptedValue, out temp)
        )
        {
            var errorMessage = "{0} is an invalid integer";
            if (bindingContext.ModelMetadata.AdditionalValues.ContainsKey("errorMessage"))
            {
                errorMessage = bindingContext.ModelMetadata.AdditionalValues["errorMessage"] as string;
            }
            errorMessage = string.Format(errorMessage, attemptedValue);
            bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorMessage);
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
            return null;
        }

        return temp;
    }
}

这篇关于int数据类型的服务器端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆