Adding a custom validator for a new country

138 views Asked by At

I am using FormEncode in Python http://formencode.readthedocs.org/en/latest/modules/national.html#module-formencode.national.

I am trying to add a custom postal code validator for Brazil. I've read the documentation, but none of it seems to be helping. Does anyone have any idea on how to approach this?

2

There are 2 answers

0
DLS On BEST ANSWER

In case anyone wants to know how to solve this using FormEncode, this is the solution I came up with

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()

Then attach this class to the validation object

national.PostalCodeInCountryFormat._vd.update({'BR': BrazilZipValidator})
1
KEERTHAN SHETTY On

Model

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

In Attribute copy paste this code and please change the namespace name to avoid the errors

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)");

            }

        }
    }
}

Controller:

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

Definitely it will work

IF THIS CODE NOT WORKING PLEASE COMMENT IT BELOW