Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle validation message from server #60

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions samples/ManagementSite/Alloy.ManagementSite.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@
<PackageReference Include="EPiServer.CMS.UI.VisitorGroups" Version="12.23.0" />
<PackageReference Include="EPiServer.CMS.UI.AspNetIdentity" Version="12.23.0" />
<PackageReference Include="EPiServer.ImageLibrary.ImageSharp" Version="2.0.1" />
<PackageReference Include="Optimizely.Headless.Form.Service" Version="0.1.0--inte-188" />
<PackageReference Include="Optimizely.Headless.Form.Service" Version="0.1.0--inte-191" />
<PackageReference Include="Optimizely.Cms.Content.EPiServer" Version="0.3.1" />
<PackageReference Include="EPiServer.Forms" Version="5.8.0-ci-021201" />
<PackageReference Include="EPiServer.Forms" Version="5.8.0-ci-021203" />
<PackageReference Include="EPiServer.OpenIDConnect" Version="3.2.0"/>
</ItemGroup>
<ItemGroup>
Expand Down
56 changes: 20 additions & 36 deletions src/@episerver/forms-react/src/components/FormBody.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useEffect, useMemo, useRef } from "react";
import React, { useEffect, useRef } from "react";
import { useForms } from "../context/store";
import { FormContainer, FormSubmitter, IdentityInfo, equals, isInArray, isNull, isNullOrEmpty, FormSubmitModel, FormSubmitResult, SubmitButton, FormValidationResult, FormCache, FormConstants, ProblemDetail, StepDependCondition } from "@episerver/forms-sdk";
import { FormContainer, FormSubmitter, IdentityInfo, isInArray, isNull, isNullOrEmpty, FormSubmitModel, FormSubmitResult, SubmitButton, FormCache, FormConstants, ProblemDetail, StepDependCondition } from "@episerver/forms-sdk";
import { RenderElementInStep } from "./RenderElementInStep";
import { DispatchFunctions } from "../context/dispatchFunctions";
import { FormStepNavigation } from "./FormStepNavigation";
Expand Down Expand Up @@ -38,8 +38,6 @@ export const FormBody = (props: FormBodyProps) => {
isSuccess = useRef<boolean>(false),
submissionWarning = useRef<boolean>(false),
message = useRef<string>(""),
isReadOnlyMode = false,
readOnlyModeMessage = "",
submissionStorageKey = FormConstants.FormSubmissionId + form.key,
isStepValidToDisplay = stepDependCondition.isStepValidToDisplay(currentStepIndex, currentPageUrl),
isMalFormSteps = stepHelper.isMalFormSteps();
Expand Down Expand Up @@ -110,31 +108,7 @@ export const FormBody = (props: FormBodyProps) => {
//submit data to API
dispatchFunctions.updateIsSubmitting(true);
formSubmitter.doSubmit(model).then((response: FormSubmitResult)=>{
//get error or success message
if(!response.success) {
//ignore validation message
showError(response.messages.filter(m => isNullOrEmpty(m.identifier)).map(m => m.message).join("<br>"));
}
//update validation message
if(response.validationFail){
let formValidationResults = formContext?.formValidationResults?.map(fr => {
let errorMessages = response.messages.filter(m => equals(m.identifier, fr.elementKey));
return errorMessages.length === 0 ? fr : {
...fr,
results: fr.results.map(er => !errorMessages.some(em => equals(em.section, er.type)) ? er : {
...er,
valid: false
})
} as FormValidationResult
}) ?? [];

dispatchFunctions.updateAllValidation(formValidationResults);

//set focus on the 1st invalid element of current step
dispatchFunctions.updateFocusOn(stepHelper.getFirstInvalidElement(formValidationResults, currentStepIndex));
}

validateFail.current = response.validationFail;
//go here, response.success always is true
isSuccess.current = response.success;
isFormFinalized.current = isLastStep && response.success;
dispatchFunctions.updateSubmissionKey(response.submissionKey);
Expand All @@ -154,6 +128,16 @@ export const FormBody = (props: FormBodyProps) => {
break;
case 400:
//validate fail
validateFail.current = false;
let formValidationResults = formContext?.formValidationResults?.map(fr => isNull(e.errors[fr.elementKey]) ? fr : {
...fr,
result: { valid: false, message: e.errors[fr.elementKey].join("<br/>") }
}) ?? [];

dispatchFunctions.updateAllValidation(formValidationResults);

//set focus on the 1st invalid element of current step
dispatchFunctions.updateFocusOn(stepHelper.getFirstInvalidElement(formValidationResults, currentStepIndex));
break;
}

Expand All @@ -178,6 +162,13 @@ export const FormBody = (props: FormBodyProps) => {
isSuccess.current = false;
},[currentStepIndex]);

//Run in-case change page by url. The currentStepIndex that get from cache is incorrect.
useEffect(()=>{
if(!isStepValidToDisplay){
dispatchFunctions.updateCurrentStepIndex(stepHelper.getCurrentStepIndex(currentPageUrl));
}
},[]);

isMalFormSteps && showError("Improperly formed FormStep configuration. Some steps are attached to pages, while some steps are not attached, or attached to content with no public URL.");

return (
Expand All @@ -199,13 +190,6 @@ export const FormBody = (props: FormBodyProps) => {
{form.properties.description}
</aside>
}
{isReadOnlyMode && readOnlyModeMessage &&
<div className="Form__Status">
<span className="Form__Readonly__Message" role="alert">
{readOnlyModeMessage}
</span>
</div>
}
{/* area for showing Form's status or validation */}
<div className="Form__Status">
<div role="status" className={`Form__Status__Message ${statusDisplay.current}`}>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { ElementValidationResult } from "@episerver/forms-sdk";
import { FormValidationResult } from "@episerver/forms-sdk";
import React, { ReactNode } from "react";

export interface ElementWrapperProps{
className?: string
isVisible: boolean,
children: ReactNode,
validationResults?: ElementValidationResult[]
validationResults?: FormValidationResult
}

export default function ElementWrapper(props: ElementWrapperProps){
const isFail = props.validationResults?.some(r => !r.valid);
const isFail = !props.validationResults?.result?.valid;

return (
<>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
import { ValidatableElementBase, ElementValidationResult, isNull } from "@episerver/forms-sdk";
import { ValidatableElementBase, FormValidationResult } from "@episerver/forms-sdk";
import React from "react";

interface ValidationMessageProps {
element: ValidatableElementBase,
validationResults: ElementValidationResult[]
validationResults: FormValidationResult
}

export const ValidationMessage = (props: ValidationMessageProps) => {
const { element, validationResults } = props;
const { validationResults } = props;

return (
<>
{element.properties.validators?.map((v, i)=> {
let valid = isNull(validationResults) || validationResults.length === 0 || isNull(validationResults[i]?.valid) || validationResults[i].valid;
return (
<span key={v.type} className="Form__Element__ValidationError" id={`${element.key}_desc`} role="alert"
style={{display: valid ? "none" : ""}}>
{v.model.message}
</span>
);
})}
<span className="Form__Element__ValidationError"
id={`${validationResults.elementKey}_desc`}
role="alert"
style={{display: validationResults.result.valid ? "none" : ""}}
>
{validationResults.result.message}
</span>
</>
);
}
4 changes: 2 additions & 2 deletions src/@episerver/forms-react/src/context/dispatchFunctions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ export class DispatchFunctions {
this._dispatch = useFormsDispatch();
}

updateValidation = (elementKey: string, validationResults: ElementValidationResult[]) => {
updateValidation = (elementKey: string, validationResult: ElementValidationResult) => {
this._dispatch({
type: ActionType.UpdateValidation,
elementKey: elementKey,
validationResults
validationResult
});
}

Expand Down
2 changes: 1 addition & 1 deletion src/@episerver/forms-react/src/context/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export function formReducer(formState: FormState, action: any) {
...formState,
formValidationResults: formState.formValidationResults.map(fv => equals(fv.elementKey, action.elementKey) ? {
elementKey: action.elementKey,
results: action.validationResults
result: action.validationResult
} as FormValidationResult : fv)
} as FormState;
}
Expand Down
16 changes: 6 additions & 10 deletions src/@episerver/forms-react/src/hooks/useElement.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect, useRef } from "react";
import { useForms, useFormsDispatch } from "../context/store";
import { useForms } from "../context/store";
import {
//models
FormContainer,
Expand All @@ -9,7 +9,6 @@ import {
ValidatableElementBaseProperties,
ValidatorType,
SatisfiedActionType,
ElementValidationResult,
//functions
equals,
getDefaultValue,
Expand All @@ -20,13 +19,14 @@ import {
FormValidator,
FormSubmission,
FormDependConditions,
FormValidationResult,
} from "@episerver/forms-sdk";
import { DispatchFunctions } from "../context/dispatchFunctions";

export interface ElementContext {
value: any,
defaultValue: any,
validationResults: ElementValidationResult[],
validationResults: FormValidationResult,
extraAttr: any,
validatorClasses: string,
isVisible: boolean,
Expand All @@ -47,7 +47,7 @@ export const useElement = (element: FormElementBase) => {
const value = (formContext?.formSubmissions ?? [])
.filter(s => equals(s.elementKey, element.key))[0]?.value ?? defaultValue ?? "";
const validationResults = (formContext?.formValidationResults ?? [])
.filter(s => equals(s.elementKey, element.key))[0]?.results ?? [];
.filter(s => equals(s.elementKey, element.key))[0] ?? {elementKey: element.key, result: {valid: true}};

//build extra attributes for element
const validatableProps = (element.properties as unknown) as ValidatableElementBaseProperties;
Expand Down Expand Up @@ -143,20 +143,16 @@ export const useElement = (element: FormElementBase) => {

if (/file/.test(type)) {
submissionValue = files;
let validationResults = formValidation.validate(files)
dispatchFuncs.updateValidation(element.key, validationResults);
dispatchFuncs.updateValidation(element.key, formValidation.validate(files));
}

//update form context
dispatchFuncs.updateValue(element.key, submissionValue);
}

const handleBlur = (e: any) => {
//call validation from form-sdk
let validationResults = formValidation.validate(value);

//update form context
dispatchFuncs.updateValidation(element.key, validationResults);
dispatchFuncs.updateValidation(element.key, formValidation.validate(value));
}

const handleReset = () => {
Expand Down
4 changes: 2 additions & 2 deletions src/@episerver/forms-sdk/src/form-step/stepHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ export class StepHelper {
*/
getFirstInvalidElement (formValidationResults: FormValidationResult[], stepIndex: number): string {
return formValidationResults.filter(fv =>
fv.results.some(r => !r.valid) &&
this._form.steps[stepIndex]?.elements?.some(e => equals(e.key, fv.elementKey))
!fv.result.valid &&
this.isInCurrentStep(fv.elementKey, stepIndex)
)[0]?.elementKey;
}

Expand Down
2 changes: 1 addition & 1 deletion src/@episerver/forms-sdk/src/form-submit/formSubmit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ export class FormSubmitter {
let value = formSubmissions.filter(fs => equals(fs.elementKey, e.key))[0]?.value;
return {
elementKey: e.key,
results: formValidator.validate(value)
result: formValidator.validate(value)
} as FormValidationResult;
});
}
Expand Down
20 changes: 12 additions & 8 deletions src/@episerver/forms-sdk/src/form-validator/formValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,13 +130,14 @@ export class FormValidator {
* @param value Value of field to validate
* @returns An object that contains validate result
*/
validate(value: any): ElementValidationResult[]{
validate(value: any): ElementValidationResult{
let result: ElementValidationResult = {valid: true, message: ""};
let validatorProps = this._element.properties as ValidatableElementBaseProperties;
if(isNull(validatorProps?.validators)){
return [];
return result;
}

return validatorProps.validators.map((v) => {
validatorProps.validators.every((v) => {
let valid = true;
switch(v.type){
case ValidatorType.CaptchaValidator:
Expand Down Expand Up @@ -164,10 +165,13 @@ export class FormValidator {
break;
}

return {
type: v.type,
valid
} as ElementValidationResult;
})
if(!valid) {
result = {valid, message: v.model.message};
return false;
}
return true;
});

return result;
}
}
16 changes: 3 additions & 13 deletions src/@episerver/forms-sdk/src/helpers/initFormState.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { FormCache } from "../form-cache";
import { StepHelper } from "../form-step";
import { FormStorage } from "../form-storage";
import { ElementValidationResult, FormConstants, FormContainer, FormState, FormSubmission, FormValidationResult, StepDependencies, ValidatableElementBaseProperties } from "../models";
import { FormConstants, FormContainer, FormState, FormSubmission, FormValidationResult, StepDependencies } from "../models";
import { getDefaultValue } from "./elementHelper";
import { equals, isNull, isNullOrEmpty } from "./utils";
import { equals, isNullOrEmpty } from "./utils";

/**
* Function to initialize FormState object
Expand All @@ -26,17 +26,7 @@ export function initFormState(formContainer: FormContainer, currentPageUrl?: str
formSubmissions = formSubmissions.concat({ elementKey: e.key, value: getDefaultValue(e) } as FormSubmission);

//init form validation
let validatableProps = e.properties as ValidatableElementBaseProperties;
let elementValidationResults = [] as ElementValidationResult[];

//some elements don't have validator
if (!isNull(validatableProps.validators)) {
validatableProps.validators.forEach(v => {
elementValidationResults = elementValidationResults.concat({ type: v.type, valid: true }); //default valid = true to hide message
});
}

formValidationResults = formValidationResults.concat({ elementKey: e.key, results: elementValidationResults });
formValidationResults = formValidationResults.concat({ elementKey: e.key, result: {valid: true, message: ""} });
});
stepDependencies = stepDependencies.concat({ elementKey: s.formStep.key, isSatisfied: false });
});
Expand Down
1 change: 1 addition & 0 deletions src/@episerver/forms-sdk/src/models/ProblemDetail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ export interface ProblemDetail {
detail: string;
instance: string;
traceId: string;
errors: Record<string, string[]>;
}
11 changes: 4 additions & 7 deletions src/@episerver/forms-sdk/src/models/states/FormValidation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,11 @@
*/
export interface FormValidationResult
{
elementKey: string
results: ElementValidationResult[]
elementKey: string;
result: ElementValidationResult;
}

/**
* Represent type of object that is element validation result
*/
export interface ElementValidationResult {
type: string
valid: boolean
valid: boolean;
message: string;
}