vlbaluk / java-validator-livr

Lightweight java validator supporting Language Independent Validation Rules Specification (LIVR)
13 stars 10 forks source link

Usually, it is better to avoid passing JSON string into the Validator #1

Open koorchik opened 6 years ago

koorchik commented 6 years ago

I guess, It makes sense to make the validator more abstract. So, it will take JsonObject and will return JsonObject. In this case it will be more flexible and you can be sure that there are no mistakes in JSONsytax.

Validator validator = LIVR.validator().init(parser.parse("{" +
                                              "name:      'required'," +
                                              "email:     [ 'required', 'email' ]," +
                                              "gender:    { one_of : ['male', 'female'] }," +
                                              "phone:     { max_length : 10 }," +
                                              "password:  [ 'required', {min_length : 10} ]," +
                                              "password2: { equal_to_field : 'password' }" +
                                              "}"),false);

or with JSON builder

JsonBuilderFactory factory = Json.createBuilderFactory(config);
JsonObject rules= factory.createObjectBuilder()
    .add("name", "required")
    .add("phone", factory.createObjectBuilder().add("max_length", 10))
    .add("address", factory.createObjectBuilder().add("nested_object", factory.createObjectBuilder()
        .add("city", "required")
        .add("zip", factory.createArrayBuilder()
            .add("required")
            .add('positite_integer')             
    ))
    .build();
Validator validator = LIVR.validator().init(rules, false)

Moreover, direct string support can be added with a simple wrapper. Besides that we allow users to create own builders.

vlbaluk commented 6 years ago

There are two methods init(JSONObject rules)and init(String rules). If string value is not valid json object you'll get FormatError like in base js implementation. Depends on necessity you can verify if object is valid before Livr usage.

koorchik commented 6 years ago

Oh, it would be great to have a alternative example (with Json builder) in docs