How can I specify a custom error message for a Joi xor()? - joi

I've got a schema where one of two optional forms can be added at runtime and one of them must be added to pass validation. I've got that bit working with the use of an xor() but I want to set a custom error message like "You must add a formA or formB to continue" instead of the default "value" must contain at least one of [formA, formB].
I've tried calling .xor().message() but I get the error
Error: Cannot apply rules to empty ruleset or the last rule added does not support rule properties
How can I specify a custom error message for a Joi xor() ?

This works for Joi version 17.2.1
const Joi = require('joi');
const schema = Joi.object().keys({
formA: Joi.string(),
formB: Joi.string(),
})
.xor('formA', 'formB')
.messages({
'object.xor': 'You must add a formA or formB to continue'
})
.required()
const data = {
formA: 'formA',
formB: 'formB'
};
const report = schema.validate(data)
console.log(report.error.message)
Output
You must add a formA or formB to continue

When both keys are missing you should use object.missing.
object.xor error appears when both keys are present.
.xor('formA', 'formB')
.messages({
'object.missing': 'You must add a formA or formB to continue',
'object.xor': 'You must provide either formA or formB'
})

Related

Formio:- Custom Error Message when the submit button is pressed without filling the required fields

I would like to change the error message that is displayed in situations where we click the submit button, but some compulsory fields are empty. The message that I receive by default is "Please check the form and correct all errors before submitting the form". I want to use instead a custom message. Is there a way to achieve this ?
You can override the error message by adding to the options when creating a form:
var options = {
i18n: {
en: {
submitError: 'My custom submission error',
}
}
}
And then later you're probably doing a call to
Formio.createForm(Formio.createForm(document.getElementById(settings.id), formDefinitionUrl, options)
which is where the options object you need is found.
Here's a list of the strings you can override this way: https://github.com/formio/formio.js/blob/master/src/translations/en.js

Date validation for custom field - SuiteCRM Version 7.10.4 Sugar Version 6.5.25 (Build 344)

I have two fields in my module called: start_date_c & end_date_c with date datatype
These fields are not mandatory fields however when i enter data into the end_date_c field I would like to make it is not less than start_date_c
I have tried the following:
https://suitecrm.com/suitecrm/forum/suitecrm-7-0-discussion/12522-how-to-validate-start-and-end-date-in-suitecrm
http://sugarmods.co.uk/how-to-add-custom-validation-to-form-fields-in-sugarcrm/
but as i am new to suiteCRM, i am not able to find positive response
You will need 2 things
Edit the file editviewdefs.php in the module you want to add the logic. This field will be autogenerated when you add the first custom field to the edit view.
Create your custom JS logic to define when the field is valid.
This logic here will add a validation callback for your
addToValidateCallback(
'EditView', // Form Name
'end_date_c', // field name
'datetime', // Field type
false, // Is required
"End date cannot be earlier than start date", // Message
function() {
//WRITE YOUR JS VALIDATION HERE, return true when is valid
});
In the editviewdefs.php find the field definition and use the displayParams to make suite/sugar add the JS for you.
array (
'name' => 'end_date_c',
'displayParams' =>
array (
'updateCallback' => 'FUNCTIONNAME',
),
),
The last step ain't needed if you already have a global custom JS (like style.js file for a custom theme).
EDIT: javascript DisplaParams will not work, so added the updateCallback option.
Now this validation works in 2 ways.
The updateCallback will be fired onChange
The addtoValidateCallback will be fired on Save.
This will give you enough flexibility to validate the form.
Simple and one linear, try following in any JS file (added in module edit view):
addToValidateDateBefore('EditView', 'start_date_c', 'date', false,'Date Start', 'end_date_c' );
worked for me.I added the following code to the fields in modules/custom_module/vardefs.php
'audited' => true,
'enable_range_search' => true,
and added the following to the start field
'validation' =>
array (
'type' => 'isbefore',
'compareto' => 'enddate',
'blank' => true,
),

grails: custom validation of just one field/property

I have a "Thing" domain class, where each Thing has an record number (which is not the automatically generated id), that the user will use to access a Thing:
class Thing {
...
String recordNumber
...
}
There is a form to look for a Thing, knowing its recordNumber:
<g:form action="search">
<input name="recordNumber">
<g:submitButton name="btn" value="go to this Thing"/>
</g:form>
I would like to use a validation process in this form: if the recordNumber is not found (Thing.findByRecordNumber(recordNumber) == null), then the input field must turn in red, and a tooltip must show the error message "record number not found".
As far as I know/read (I'm a grails rookie), this has to be written as a constraint in the Thing class:
static constraints = {
recordNumber validator: { n -> Thing.findByRecordNumber(recordNumber) }
}
The problem is: I do not have in this form all the "Thing" properties to populate, just the recordNumber one, so I just can't call
new Thing(params).validate()
How to call validation on just one field, not on the whole object ?
If this is your main question, although I see others there:
"How to call validation on just one field, not on the whole object ?"
You can pass a list of values to validate and it will only validate those properties
new Thing(params).validate(["recordNumber"])
http://grails.org/doc/latest/ref/Domain%20Classes/validate.html
Validation is for constraints for domain class properties. You need an action in your controller:
def search = {
if(params.recordNumber && Thing.findByRecordNumber(params.recordNumber)){
redirect(action: "show", params:[id:Thing.findByRecordNumber(params.recordNumber).id])
}else{
flush.message = "No record found"
render(view:'VIEW_WITH_SEARCH_FORM')
}
}
If you want to validate without refreshing page, write a javascript code.

Validation errors using datamapper gem

I’m using Datamapper (1.2.0) and Sinatra (1.3.2). I have a model and a property of the model is Employee ID. This is a mandatory field so whenever this is not been entered by the user I need to throw validation error.
Datamapper intelligently identifies the name of the property as 'Employee' (cuts down id part) and displays the error as 'Employee can't be blank' and 'Employee should be an integer'.
So I tried to override these error messages. I could able to override the 'Employee can't be blank' but cannot able to override the other.
property :employee_id, Integer, :required => true, :unique => true,
:messages => {
:presence => "Employee ID cannot be blank.",
:is_unique => "Employee ID should be unique."
}
What should be the hash key I need to use to override the 'not_an_integer' error?
I think the message key you’re looking for is :is_number. Where this is documented is a bit hidden away. (I actually looked for it in the source).
Also, it seems to be if you have any :messages hash in the property options then the default messages are replaced with nil if you don’t specify a custom message for that validation.

How to display ad hoc constraints form validation messages?

ScalaForms
In the example linked here there is this example about form validation:
// You can also define ad-hoc constraints on the fields:
val loginForm = Form(
tuple(
"email" -> nonEmptyText,
"password" -> text
) verifying("Invalid user name or password", fields => fields match {
case (e, p) => User.authenticate(e,p).isDefined
})
)
Via binding errors some constraints are displayed in my form. (Like the nonEmptyText, that gets a extra line behind the field stating This field is required. See:
loginForm.bindFromRequest.fold(
formWithErrors => // binding failure, you retrieve the form containing errors,
value => // binding success, you get the actual value
)
If I do a .toString to the formWithErrors i get this for the nonEmptyText constraint:
Form(ObjectMapping2(<function2>,<function1>,(Email adress,FieldMapping(,List(Constraint(Some(constraint.required),WrappedArray())))),(Password,FieldMapping(,List(Constraint(Some(constraint.required),WrappedArray())))),,List(Constraint(None,List()))),Map(Password -> test, Email adress -> ),List(FormError(Email adress,error.required,WrappedArray())),None)
The latter part is a FormError List: List(FormError(Email adress,error.required,WrappedArray())),None) which is a case class: case class FormError (key: String, message: String, args: Seq[Any]) where key is defined as: The error key (should be associated with a field using the same key)..
The FieldConstructor picks this up and makes the 'Email adress' input box go red and add the error message ('This field is required').
Displaying the ad hoc constraints?
So when the form fields are all filled the username and password are checked:
verifying("Invalid user name or password", fields => fields match {
case (e, p) => User.authenticate(e,p).isDefined
})
But i dont know how to display the 'Invalid user name or password' to the user. The .toString of the FormError List of formWithErrors is:
List(FormError(,Invalid user name or password,WrappedArray())),None)
The Key part is empty.
Question
How do i display the ad hoc error?
I even tried:
BadRequest( views.html.test( formWithErrors ) ).flashing( "error" -> "Invalid user name or password." ) },
but for some reason its not working via the Flash either :(. This #flash.get("error").getOrElse("no 'error'") gives me 'no error' each time.
Actually, a form can have errors attached to it, so then when a bind from request fails validating constraint, a new form is created based on the given one, but filled in with errors.
Such errors list is composed of FormError which refers a Form Field and overrides toString to show its embed message.
This way if you wish to show all messages at once, you can simply formWithErrors.errors.mkString("<br>") for instance (in you template or flashing it).
There are a lot of ways and some common ones are described here http://www.playframework.org/documentation/2.0.2/ScalaFormHelpers. You might define your own field constructor as well.
To conclude, my advice would be that you should use helpers amap (for instance #inputText and co) because they already contain the logic to show helpers, tips and errors when available.
Edit
I missed the hint about the flash problem... you've probably forgotten to add (implicit flash: Flash) to you template param list. (don't forget to flag the request as implicit as well in your action definition)