Tagbangers Blog

RadDataForm validation with propertyValidate

Handling a validation can be quite a mess depending on the case, but let’s have a look at a simpler example for validating an empty field.


// my-form.html
<RadDataForm ...>
   <TKPropertyGroup ...>
      <TKEntityProperty tkPropertyGroupProperties name="username" displayName="username" index="0">
         <TKNonEmptyValidator tkEntityPropertyValidators errorMessage="Username can't be empty"></TKNonEmptyValidator>
      </TKEntityProperty>
      ...
   </TKPropertyGroup>
</RadDataForm>


Validating an empty field is pretty simple as we can use the TKNonEmptyValidator tag for displaying the error message.



But what if our validation is more complicated than that? let's say we don't want the users to use certain words for their username


In this case, we can use the propertyValidate event provided by the RadDataForm itself to write our validation


propertyValidate: This event is fired while the value is validating and allows you to interfere and change the validation result.


Let's rewrite our code


We can pass our onPropertyValidate function to propertyValidate attribute on RadDataForm


// my-form.html
<RadDataForm ... (propertyValidate)="onPropertyValidate($event)">
   <TKPropertyGroup ...>
      <TKEntityProperty tkPropertyGroupProperties name="username" displayName="username" index="0"></TKEntityProperty>
      ...
   </TKPropertyGroup>
</RadDataForm>
// my-form.js

onPropertyValidate(args) {
   let validationResult = true;
   const propertyName = args.propertyName;
   const valueCandidate = args.object.getPropertyByName(propertyName).valueCandidate;

   if (propertyName === "username" && valueCandidate === "foo") {
      args.entityProperty.errorMessage = "Username is invalid";
      validationResult = false;
   }

    args.returnValue = validationResult;
}




and we will get an error when we're trying to use foo for our username


We can also perform more complicated validation with this like username/email asynchronous validation and more