First steps – Defining our rules

The Aurelia validation plugin is based on standard rules. We need to define our own set of rules using the ValidationRules class. This class has some static methods that receive our values and verify that the input value meet our requirements. Also, one validation rule must have one predefined format. The first method we will explain is ensure():

 ValidationRules.ensure('myValidatedProperty')

This method accepts one argument that will be our property name that we want to validate. Also, in case you were validating an object, you are allowed to pass anonymous functions as a parameter:

 ValidationRules.ensure(u => u.firstName)

The second method we will explain is displayName(). This is not required but is useful if you need to show this property in one predefined format in your validation messages; consider this example:

 ValidationRules.ensure(u => u.firstName).displayName('User name')
Error message: The user name is required.

Finally, we need to define our set of rules that will apply to that field; some of the most used are as follows:

  • required() prevents the user from submitting null or blank values
  • matches(regex) helps us ensure that the input value meets a predefined format, and is common on date fields
  • email() is an easy way to ensure that the email is in the right format
  • minLength(length) and maxLength(length) validate the length of string properties

If our user's first name should never be null, the validation rule will be this:

    ValidationRules.ensure('u => u.firstName').displayName('First name')
        .required().withMessage(`${$firstName} cannot be blank.`);

Did you note something different? Yes, we are using the withMessage() method to customize our validation error message. The thing becomes more interesting.

What if you need these validation rules to apply just for one object? Don't worry, Aurelia has the problem solved. You need to tag the object you want to apply the rule on; the example is self-explanatory:

   // User.js class inside our models folder
export class User { firstName = ''; lastName = ''; } export const UserRules = ValidationRules .ensure('firstName').required() .ensure('lastName').required() .on(User);

We are almost ready. Now, we need to configure our form controller with the recently created validation rules:

import { inject, NewInstance } from 'aurelia-dependency-injection';
import { ValidationController } from 'aurelia-validation';
import { User, UserRules } from '../models/User' @inject(NewInstance.of(ValidationController)) export class UserRegisterForm { constructor(userValidationController) {
this.user = new User(); // 1
this.formValidator = userValidationController; //2
this.formValidator.addObject(this.user, UserRules); //3
} }

Maybe you are wondering why we need this NewInstance.of() statement? Well, for each validation rule we are applying, we need a single controller to validate it. So, with this statement, we just ensure that a new ValidationController instance is created.

Now let's explain what is occurring inside our constructor method:

  • Line 1: We are creating a new instance of the User object to use his properties in our form.
  • Line 2: We are assigning the new ValidatorController instance into our formValidator object.
  • Line 3: We are saying to our formValidator that the evaluated object is our user instance, and will use the imported UserRules.

 

Other way to configure our formValidator is defining the properties and rules inside the validate() method: 

formValidator.validate({ object: user, propertyName: 'firstName', rules: myRules });

In our submit() method, we just need to add the following:

formValidator.validate()
      .then(result => {
if (result.valid) { // validation succeeded } else {
        // validation failed
      }
});

Lastly, we need to tell our template where the validators will be placed:

    <input type="text" value.bind="user.firstName & validate">

    <input type="text" value.bind="user.lastName & validate">

The first value will be passed as a parameter to the ensure() function. Hey, wait a second! We need to specify where our error messages will be placed! Well, that's really simple, we would implement an error list like this:

<form>
      <ul if.bind="formValidator.errors">
        <li repeat.for="error of formValidator.errors">
          ${error.message}
        </li>
      </ul>
</form>

Alternatively, if you want to display the message beside the wrong input element, you can use the <span> tag and other very interesting custom attribute: validation-errors

<div validation-errors.bind="firstNameErrors"> 
<
label for="firstName">
First Name</label> <input type="text" class="form-control" id="firstName" placeholder="First Name" value.bind="user.firstName & validate"> <span class="help-block" repeat.for="errorInfo of firstNameErrors"> ${errorInfo.error.message} </span>
</div>

The validation-errors attribute contains all validation errors regarding to the specified element (in this case firstNameErrors).

Now, start putting validation rules across your application forms! See you in the next section!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.180.131