Custom validation

Hi all:

So far I’m in love with Anvil. Many thanks to the team and community. You’ve helped me plenty and given me motivation to get to work on some ideas I had that I couldn’t implement before.

In regards to my question, I’ve tried searching for a similar topic but couldn’t find the answer. Basically, I need a custom form validation, but I couldn’t figure out how to implement it. The excelent post by Meredydd helped me a lot and wanted to use it as a basis adding a custom form validation to figure out if the id number of any Chilean persona (which in Chile we call RUT) was valid or not.

The way a RUT works is that it contains a number, followed by a dash and then a verifying digit (called dv). If the DV is not consistent with the number, then the RUT is not valid. In order for it to be consistent, certain conditions have to be met. Here’s a function that contains such conditions:

def verifyRut(rut):
    rut = rut.upper();
    rut = rut.replace("-","")
    aux = rut[:-1]
    dv = rut[-1:]
	rever = map(int, reversed(str(aux)))
	factors = cycle(range(2,8))
	s = sum(d * f for d, f in zip(rever, factors))
	res = (-s)%11
 
	if str(res) == dv:
		return True
	elif dv=="K" and res==10:
		return True
	else:
		return False

My question is, how can I adapt this function within Meredydd’s method so I can I also use some of its functionalities?

Have you checked out this blog post on a guide to using the Validation library?

https://anvil.works/library/form-validation

Hi. Yes, I did. I’m using that same library. I just couldn’t get to adapt the custom validation to the library.

You can adjust the 3rd argument in the setup…


self.validator.require(
  self.my_component,
  ['change', 'lost_focus'],
  lambda component: return component.text != '',
  self.label_to_display_if_invalid,
)

…to be a custom function - basically the function you wrote but instead of taking text as an argument it should take a component.

3 Likes

Many Thanks. That did it:

  def require_valid_rut(self, text_box, error_lbl=None, show_errors_immediately=False):
    self.require(text_box, ['lost_focus'],
                 verifyRut,
                 error_lbl, show_errors_immediately)
1 Like