Thursday, December 28, 2017

Inadvertent Example of the Benefit of vadacl's Class-Based Validation Rules

While I was verifying that my vadacl validation library wasn't adversely affected ("broken") by any changes in the latest version of Angular (5.1.2), I discovered that one of my validations wasn't working correctly.

In two of the forms in the vadacl demo I have up on GitHub, there is a "Gender" form field where the user is only allowed to enter "M" or "F".  As I was testing the validation on that field, I was surprised to see that while the "F" validation was being enforced, the "M" validation was allowing any word that started with the letter "M".

The validation rule was defined within the UserProfile object class in the demo:  one of the main features of vadacl is that you can define your validations in a class, like so...
validations: { [ index: string ] : PropertyValidations } = {
    firstName: {
      maxLength: { maxLength: 25 },
      required: {}
    },
    lastName: {
      maxLength: { maxLength: 25, message: 'Your last name cannot be longer than 25 characters.'},
      required: { message: 'Your last name is required.' }
    },
    username: {
      maxLength: { maxLength: 30, message: 'Your username cannot be longer than 30 characters.'},
      required: { message: 'You must have a username.' }
    },
    password: {
      minLength: { minLength: 6, message: 'Your password must be at least 6 characters long.' },
      required: { message: 'You must provide a password.' },
    },
    age: {
      pattern: { pattern: '[0-9]*', message: 'Enter your age as an integer.' }
    },
    gender: {
      pattern: { pattern: 'M|F', message: 'Enter your gender as "M" or "F".' }
    }
};

...and then utilize them in your components. The rule invoked the Pattern Validator method using the following pattern:

M|F

I thought that the either/or pipe would limit the valid value to either "M" or "F", but apparently not, and by virtue of being in front of the pipe the male validation allowed for characters beyond the "M".  So I fixed the validation by changing the pattern to:

[MF]{1}

If this same issue had come up in a different application that used normal Angular reactive form validation, I would have had to correct the pattern in the form controls in both of the components, rather than just once.

 

No comments:

Post a Comment