John
John

Reputation: 815

Validate user input

I've implemented the following rules in my Xtext DSL:

House:
    'House' name=ID
    description=STRING?
    ('height' height=DOUBLE heightUnit=UNIT)? &
    ('width' width=DOUBLE widthUnit=UNIT)? &
    'end' 'House' 
    ;

enum UNIT:
        m = 'm' |
        cm = 'cm'
    ;

It allows me to define the following, using the editor based on that DSL:

House MyHouse
    "This is my house"
    height 15.5 m
    width 3000.2 cm
end MyHouse

How can I validate the units, defined by the user? For example, both height and width should have the unit m and if the user defines something different (cm for example), the editor should show an error.

I've checked this site, which describes how to create validation rules, but where do I have to register them, so that they can work perperly?

UPDATE: As described in Ravens comment under his post, I've used reverse engineering and added the correspondig package and class, which now looks like the following:

package com.language.validation

import com.language.mylanguage.House
import org.eclipse.xtext.validation.Check

class MylanguageValidator {

    @Check
    def unitCheck(House house) {
        val hWidth = house.width

        if (hWidth != null) {
            if (!hWidth.equals("m")) {
                val errorMsg = "House width must be defined in m";
                // error method undefined
            }
        }
    }
}

The Package of the class is inside the plug-in project com.language.mylanguage. I am trying to validate, if the user used m as the unit. If not, an error message should appear. The method error() is undefined. Do I have to import or extend another class?

Upvotes: 0

Views: 106

Answers (2)

Stefan Oehme
Stefan Oehme

Reputation: 457

Your language's mwe2 workflow is probably missing the ValidatorFragment. This fragment creates the stub and does the guice bindings for you so you only have to fill the class with logic.

Upvotes: 1

Raven
Raven

Reputation: 3516

In your project folder you have a few packages and one of them is named yourDSLName.validation.
In this package there is a xtend class where all validation rules have to be specified. So in there you add your test-method in the form

@Check
def unitCheck(House house) {
   val hUnit = house.getHeigthUnit()
   val wUnit = house.getWidthUnit()

   if(hUnit != null && wUnit != null && !hUnit.equals(wUnit)) {
       val errorMsg = "Units have to be the same!"
       error(errorMsg, #Package.eINSTANCE.House_widthUnit)
   }
}

Note: You have to replace the #Package with the packageName of your DSL.

UPDATE:
You have to extend the class "AbstractMyLanguageValidator"

Greetings Raven

Upvotes: 1

Related Questions