Formik Yup Validation of array of strings not working - formik

I am using formik validations with Yup. I have created a customize react select component to select multiple options. When the user selects an option, its id will push to an array. This is a required field. So I have used this code to validate it, but the error message will not appear.
interest: Yup.array().of(Yup.string().required("This field is required"))
Then I tried this one. Then the error message will appear but when I select the options, the error message will not disappear.
interest: Yup.array().min(1, "at least 1").required("This field is required")
This is initial values:
const formik = useFormik({
initialValues: {
interest:[]
}
})
Also, I need to set the maximum value is 10.

Formik will add the error to the errors object that you can get from the Formikbag. If the error is being added to the list then you can choose to show an error message by displaying it in your component. To my knowledge it won't display the error automatically unless you use the formik ErrorMessage component.
Example: https://formik.org/docs/api/errormessage

Related

D365 - UCI - A validation error occurred. The value 895390001 of 'MULTISELECT' on record of type ENTITY' is outside the valid range. Accepted Values:

I am trying to use the Multiselect option set and want to build it dynamically, the addOption() is populating the multiselect field correctly, but on save of record it is prompting the validation error.
On change of contact lookup, I am populating the abc_multiselect field. It is populating fine dynamically then user selects the required options from multiselect field, but on save of record (Ribbon Save button not custom save event of form) the CRM is not accepting the values.
MSCRM Version
Server version: 9.2.22081.00182
Client version: 1.4.4647-2208.1
function polulate(executionContext){
var formContext = executionContext.getFormContext();
var multiselect = formContext.getControl("abc_multiselect");
var high = {value : 895390001, text : "High"};
multiselect.addOption(high);
}
The error is;
On Popup
One or more of the option values for this picklist are not in the range of allowed values.
Details
Exception Message: A validation error occurred. The value 895390001 of 'abc_multiselect' on record of type 'abc_ENTITY' is outside the valid range. Accepted Values:
ErrorCode: -2147204326
HexErrorCode: 0x8004431a
ErrorDetails:
ApiExceptionSourceKey: Plugin/Microsoft.Crm.ObjectModel.TargetAttributeValidationPlugin
ApiStepKey: fc743e7d-fbea-4695-bdb9-7d78334c8474
ApiDepthKey: 1
ApiActivityIdKey: 3907c6d7-ef4a-437e-946f-55e0f956fc3e
ApiPluginSolutionNameKey: System
ApiStepSolutionNameKey: System
ApiExceptionCategory: ClientError
ApiExceptionMessageName: PicklistValueOutOfRange
ApiExceptionHttpStatusCode: 400
HelpLink: http://go.microsoft.com/fwlink/?LinkID=398563&error=Microsoft.Crm.CrmException%3a8004431a&client=platform
TraceText:
[Microsoft.Crm.ObjectModel: Microsoft.Crm.ObjectModel.TargetAttributeValidationPlugin]
[fc743e7d-fbea-4695-bdb9-7d78334c8474: TargetAttributeValidationPlugin]
Activity Id: 28d5f67f-bf24-4eca-9124-cf95cf06dc30
I also tried to make all option set values hard coded (Added during the multiselect field creation), it worked smoothly. No issue ! But on dynamically population; on save, the CRM is not accepting the values.
I have tried this , this, this and this but all in vain.
Any one can guide, what is missing?
Update 1
function polulate(executionContext){
var formContext = executionContext.getFormContext();
var multiselect = formContext.getControl("abc_multiselect");
multiselect.clearOptions();
var high = {value : 895390001, text : "High"};
multiselect.addOption(high);
}
I also checked by changing the value from 895390001 to 895390000 and even to 100 and 101 but still same issue.
https://stackoverflow.com/a/48011975/5436880
This should solve your issue? most probably option set does not have 895390001 or it is already selected. you could also try to clear all option sets and then add
clear options
For using addOption those options need to be there in metadata first. You cannot add an option that is not present in metadata. Example can be Suppose you have Option A, 1 and 3 in Metadata. now you want to add another option 4 using Javascript "addOption", it is not possible.
In your case, get a maximum possible set or options in the optionset now onload of form or Onchange of field "removeOption " the options that are not required.

Laravel custom request validation

i have been trying in create check on form validation on laravel
i need to query input with date and check more than check with many messages
like
if(){
$this->errorSchema->addError($error, $name); //symfony 1 way
}
how and where should i do that i have been thinking in creating custom validtaion but it returns true or false i need the date in the query to display like "this place is used for user XXX" XXX is data i got in the query
i want to return multi error if some record exist like
$resultset = 'select person form events where date < "some date"';
if ($resultset[enddate] > 'somedate'){
my error message should be "you cant add this event as $resultset['person'] overlape in this date "
}elseif($resultset[startdate] > 'somedate'){
i need here to return deffrent error message like "start date is overlapping with resultset['person']"
}
i am using requests class in laravel so please recommend me a method to override or any other way to this in laravel
thanks in advance
You can try to SELECT data which you'd like to return, your "XXX", from table by user's input.
Simple SELECT *** FROM table WHERE smth = user's_input;
If it return smth, you can just add it to your validator such as: "this place is used for user".$smth;
Else (if nothing returned, you send to user your default answer.)
Also if you add more code it will be easier to help you :)

Grails parent child form validation

I have an Invoice
class Invoice{
static hasMany = [lineItems: InvoiceItem]
double total
}
class InvoiceItem{
String description
double price
double qty
}
My issue is with form validation. If a user enters a string or invalid number format in either price or qty I get a
Failed to convert property value of type java.lang.String
to required type double for property price
BUT the error is in the Invoice object NOT in the LineItems object therefore I cannot highlight in RED the form appropriately. (And field value remains at zero when displayed so message is somewhat meaningless to user)
I was thinking of using COMMAND object with String parameters and validating their numeric value but I can't figure how to bind the InvoiceItem List.
What is the appropriate Grails way?
I could do all validation on the client side in javascript but that is not my question
You can do it with command objects. You need to read:
http://blog.peterdelahunty.com/2009/01/cool-way-to-dynamically-add-entries-to.html
command object data binding
Grails command object data binding
http://grails.1312388.n4.nabble.com/validating-nested-command-objects-td1346994.html

Propel ORM Version 1.6.4 -understanding validators

(reworded the question hours later to be more descriptive)
I need a little advice on understanding Propel setters/validators in a standalone (non-framework) development.
The documentation on validation states:
Validators help you to validate an input before persisting it to the database.
... and in validator messages we can provided coherent advice on where users can correct entries that don't pass Propel validation.
The sample usage of a validator reads:
$user = new User();
$user->setUsername("foo"); // only 3 in length, which is too short...
if ($objUser->validate()) {
...
The problem I have found with this is 'what if you cannot setXXX() in order to validate it?'
I have a column type DATE and I invite a visitor to enter a date in a web form. They mistype the date and submit 03/18/20q2
I would hope that one of my custom validators would be able to report a validator message and return the form once more to the user to be amended, however this occurs first:
Fatal error: Uncaught exception 'PropelException' with message 'Error parsing date/time value: '03/18/20q2' [wrapped: DateTime::__construct() [<a href='datetime.--construct'>datetime.--construct</a>]: Failed to parse time string (03/18/aaa) at position 5 (/):
In my tests I couldn't get any simple or CustomValidator to fire once I'd written (for example):
$event= new Event();
$event->setDateStart($form_value_for_date); // where values is "03/18/20q2"
I understand why this is so - it would not make sense to be able to create and try to manipulate a new object if you cannot rely on its fields, even before you save it.
The dilemma this gives me is:
If a fatal error can result from invalid entry preventing Propel validation from handling it for me (and therefore the user) and sending back a useful message, should I bother with Propel validation as well as my own security/courtesy validation ?
I cannot find any mention in the docs of what happens if you give Propel - for whatever reason - a value it doesn't anticipate for the field, or how to handle it.
I do hope this makes sense and that someone can point me at a method that will mean I only need to validate input in one place.
I've hacked together a rough ready solution that will allow me to:
Pre-validate a field against a CustomValidator without setting it in the new object
Retrieve the validator's message for return to the user
I take the form input, sanitise it of course, and then create an object:
$event = new Event();
With my user form in mind, I then pre-check the field I know will fatally fall over if the content's bad, and only set the field in my new object if it would validate:
if ($check = $event->flightCheckFail('StartingDate','DateValidator',$sanitisedFormVal))
echo $check;
else
$event->setStartingDate($sanitisedFormVal);
Method flightCheckFail() will return false if the data from the form would validate against the field, it returns the validator's error message if it would fail.
The method's added to my Event class as follows. Its arguments are the field name, the class of the CustomValidator (which simply runs an strtotime check), and the sanitised form value:
public function flightCheckFail($name,$validatorClass,$value) {
$colname = $this->getPeer()->getTableMap()->getColumnByPhpName($name)->getName();
$validators = $this->getPeer()->getTableMap()->getColumn($colname)->getValidators();
foreach($validators as $validatorMap)
if ($validatorMap->getClass() == $validatorClass) {
$validator = BasePeer::getValidator($validatorMap->getClass());
if ( $validator->isValid($validatorMap, $value) === false)
$failureMessage = $validatorMap->getMessage();
} // if $validatorMap->getClass() == $validatorClass
if($failureMessage)
return $failureMessage;
else
return false;
}
I should be able to use this to work around handling dates in forms, but I'll need to check what other types in Propel might require this sort of handling.
I can stop the form handling wherever this reports a validator error message and send it back. When the user enters valid data, Propel (and normal Propel Validation) gets to continue as normal.
If anyone can improve on this I'd love to see your results.
You could also use a MatchValidator, with a date RegExp, no need for extra functions

How to get Pylons formencode validator to ignore some fields

I have a form that has some input text boxes and well as some select boxes. I have validation working perfectly on the textboxes. I don't care if any of the select boxes are left defualt or not, but everytime I submit the form it goes to a pylons error page saying "Invalid: Please enter value for ..." But I don't want that to happen.
here is my validator function:
class Registration(formencode.Schema):
allow_extra_fields=True
first_name = formencode.validators.String(strip=True, not_empty=True)
last_name = formencode.validators.String(strip=True, not_empty=True)
address = formencode.validators.String(strip=True, not_empty=True)
phone = formencode.validators.PhoneNumber(strip=True, not_empty=True)
email = formencode.validators.Email(resolve_domain=True, not_empty=True)
messages = {
'tooLow': "You must be at least 18 in order to register for an event.",
'tooHigh': "You obviously are not that old. Please enter your actual age.",
}
age = formencode.validators.Int(min=18, max=999, not_empty=True, messages=messages)
I thought with allow_extra_fields = True it would allow for fields in the form that aren't supplied in the function to pass if left blank/default. I have select boxes named heard, frequency, and level that should be ignored.
Any help here would be greatly appreciated.
On your formencode.validators methods:
Use not_empty=False if your form is submitting the fields and the values are empty strings. The param not_empty false is how you say: empty is a valid value.
If the fields do not exist then use if_missing = None which will set your result to None.
I think you should add the following line to it
filter_extra_fields = True

Resources