为新国家/地区添加自定义验证程序

时间:2015-07-09 19:18:08

标签: python formencode

我在Python http://formencode.readthedocs.org/en/latest/modules/national.html#module-formencode.national中使用FormEncode。

我正在尝试为巴西添加自定义邮政编码验证器。我已阅读文档,但似乎没有任何帮助。有没有人知道如何处理这个问题?

2 个答案:

答案 0 :(得分:0)

如果有人想知道如何使用FormEncode解决这个问题,这就是我提出的解决方案

class BrazilZipValidator(validators.Regex):
messages = {
    'invalid': _('Please enter a valid code (nnnnn-nnn or nnnnnnnn)')
}
regex = re.compile(r'^([0-9]{8})$|^([0-9]{5}-[0-9]{3})$')
strip = True

def _to_python(self, value, state):
    self.assert_string(value, state)
    match = self.regex.search(value)
    if not match:
        raise formencode.Invalid(self.message('invalid', state), value, \
                                 state)
    return match.group()

然后将此类附加到验证对象

national.PostalCodeInCountryFormat._vd.update({'BR': BrazilZipValidator})

答案 1 :(得分:-2)

型号

[checkCountry(AllowCountry = "India,USA,SriLanka", ErrorMessage = ("Please choose a valid country eg.(India,USA,SriLanka"))]
public string Country { get; set; }

在属性副本中粘贴以下代码,请更改名称空间名称,以避免错误

using System.Linq;


namespace WebApp.Models
{
    public class checkCountryAttribute : ValidationAttribute
    {
        public String AllowCountry { get; set; }

        protected override ValidationResult IsValid(object country, ValidationContext validationContext)

        {

            string[] myarr = AllowCountry.ToString().Split(',');

            if (myarr.Contains(country))

            {

                return ValidationResult.Success;

            }

            else

            {

                return new ValidationResult("Please choose a valid country eg.(India,USA,SriLanka)");

            }

        }
    }
}

控制器:

[ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult Student(Student submit)
        {
            if (ModelState.IsValid)
            {
                ViewBag.Message = "Succesfully Submitted";
                return View("Student");
            }
            return View();
        }

肯定可以使用

如果此代码不起作用,请在下面注释