简体   繁体   English

来自数据库的MVC 5验证数据注释

[英]MVC 5 Validation Data Annotations from Database

I have been looking for ways to make a custom validation (its haaaaaard) using data from a DB. 我一直在寻找使用数据库中的数据进行自定义验证的方法。 For example, i have in my project a EntityFramework enviromment. 例如,我在我的项目中有一个EntityFramework环境。 So, how I can do to make a custom validation using data annotations and compare some value with a DB item? 那么,如何使用数据注释进行自定义验证并将某些值与数据库项目进行比较呢?

For example: 例如:

I want o validate a field call "Code" to see if exists in the DB. 我想o验证字段“代码”以查看数据库中是否存在。 If not, i want a message "Error: you must use a valid code" 如果没有,我想要一条消息“错误:您必须使用有效的代码”

Can you help me? 你能帮助我吗?

Thanks! 谢谢!

Done! 完成!

With the help of Stephen Muecke and this pages: 在Stephen Muecke和以下页面的帮助下:

But the credits is for Stephen and the Remote Validation. 但是功劳是斯蒂芬和远程验证。 Thanks!! 谢谢!!

Controller: 控制器:

public JsonResult ExisteCodOp(string Codigo_Operador)
    {
        ModeloDePool1 ModeloPool1 = new ModeloDePool1();

        bool ExisteCodOp = ModeloPool1.CheckCodOp(Codigo_Operador);

        if (ExisteCodOp == false)
        {
            return Json("No existe el KVD escrito.", JsonRequestBehavior.AllowGet);
        }
        else
        {
            return Json(true, JsonRequestBehavior.AllowGet);
        }

Model: 模型:

        [Required]
    [RegularExpression(@"[Tt,Ss]-\d\d", ErrorMessage="Debe colocar un Código de Operador válido.")]
    [Remote("ExisteCodOp","Pool")]
    [DisplayName("Código Operador")]
    public string Codigo_Operador { get; set; }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM