Untitled

 avatar
unknown
javascript
3 years ago
32 kB
3
Indexable
/*************************************************************************************************\
@author:        Ben Allington
@company:       NHS
@history:       BA 15/09/2020 - Created.                
*************************************************************************************************/
import { LightningElement, api, track, wire } from 'lwc';
import {fireEvent, registerListener, unregisterListener } from 'c/pubsub';

import {FlowAttributeChangeEvent} from 'lightning/flowSupport';

import { FlowContextProvider } from 'c/nhsFlowContextProvider';
import {scrollToElement, getGridSize, getSanitizedData} from 'c/nhsUtils';
import { CurrentPageReference } from 'lightning/navigation';

import phoneFormat from '@salesforce/resourceUrl/phoneformat';
import { loadScript } from 'lightning/platformResourceLoader';

const ERROR_MESSAGE_DEFAULT = 'Select an option';
const ERROR_MESSAGE_PROHIBITED = 'Your booking reference number must not include special characters, like / # £ : ; or %';
const ERROR_MESSAGE_CHARACTER_LIMIT = 'Your booking reference number must not be more than 12 characters';
const PAGE_ERROR_RADIO_TYPE = 'radioGroup';
const RADIO_CSS_STANDARD = 'nhsuk-radios';
const FORM_GROUP_CSS_STANDARD = 'nhsuk-form-group';
const FORM_GROUP_CSS_STANDARD_ERROR = 'nhsuk-form-group nhsuk-form-group--error';
const BULLET_LIST_DELIMITER = ';';
const INPUT_CSS_STANDARD = 'nhsuk-input';
const INPUT_CSS_STANDARD_INVALID = 'nhsuk-input--error';
const INPUT_WIDTH_CSS_STANDARD = 'nhsuk-input nhsuk-u-width-';
const INVALID_PHONE = ', like +441234567890';
const PHONE_REGEX = /(\+44)[1-9][0-9]\d{7,8}$/;
const INDENTIFY_LETTERS = /^[^a-zA-Z]+$/;
const INVALID_EMAIL = ' in the correct format, like name@example.com';
const INVALID_POSTCODE = 'Enter a postcode, like AA1 1AA';
const EMAIL_REGEX = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
const POST_CODE_REGEX = /([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2})/g;
const NUMBER_REGEX = /^\d*$/;
const VOWEL_REGEX = /^[aeiou]/i;
const FLOW_VALIDATION_RESP_EVENT_NAME = '@salesforce/messageChannel/LMSFlowValidationResponse__c';
const FLOW_VALIDATION_REQ_EVENT_NAME = '@salesforce/messageChannel/LMSFlowValidationRequest__c';
const SCROLL_TO_EVENT_NAME = '@salesforce/messageChannel/LMSFlowScrollToRequest__c';
const DISPLAYELEMENT_INPUTELEMENT_CONNECTION = '@salesforce/messageChannel/LMSDisplayToInputConnection__c';

export default class RadioButtonElement extends LightningElement {
    isSubscribedToValidationRequestEvent = false;
    handleValidationRequestHandler;
    isSubscribedToScrollToEvent = false;
    scrollToHandler;
    isSubscribedToConnectionRequestEvent = false;
    handleConnectionRequest;
    phoneFormatInitialized = false;

    @wire(CurrentPageReference) pageRef;
    
    @api titleText;
    @api hint1Text;
    @api hint2Text;
    @api labelText;
    @api hintLabelText;
    @api selectedRadio;
    @api requiredField;
    @api hiddenInputLabels;
    @api customErrorMessage;
    @api customOptionList;
    @api useHints;
    @api customHintsList;
    @api customOptionTypeList;
    @api customOptionInputLabelList;
    @api inputWidth;
    @api enteredValue = null;
    @api fieldNameErrorLabel;
    @api numberExampleForError;
    @api maxChar;
    @api minChar;
    @api identifier
    
    @api labelForSummary;
    @api dependentValueForSummary;
    @api dependentLabelForSummary;
    @api requiredInSummary;
    @api sortOrderNumber;

    @track radioOptions = [];
    @track pageErrors = [];
    @track selectedValue;
    @track selectedOptionType;
    @track errorShowPhone = false;
    @track errorShowInternationalPhone = false;
    @track errorShowEmail = false;
    @track enteredText = null;
    @track errorShowNumber = false;
    @track errorShowPostCode = false;
    @track invalidNumber;
    @track enteredTextLabel = '';
    @track inputCssError = false;
    @track radiosGenericErrorDetail;

    connectedCallback() {        
        if(!this.phoneFormatInitialized){
            loadScript(this, phoneFormat + '/phone-format-global.min.js')
            .then(() => {
                this.phoneFormatInitialized = true;
                this.handleSubscribe();
                this.subscribeScrollTo();
                if(this.identifier){
                    this.handleLWCConnectionSubscribe();
                }
                if(this.customOptionList){
                    this.parseOptionList();
                } else {
                    this.getOptionList();
                }
            })
            .catch(error => console.log(error));
        }

        if(this.requiredField == null || !this.requiredField){
            this.requiredField = false;
        }
        if(this.customErrorMessage == null || !this.customErrorMessage){
            this.customErrorMessage = ERROR_MESSAGE_DEFAULT;
        }
    }

    renderedCallback(){
        if(!this.identifier){
            if(this.labelText){
                var labelId = this.template.querySelector('.nhsuk-select-label').id;
                this.template.querySelector('.nhsuk-fieldset').setAttribute('aria-labelledby', labelId);
            } 
            if(this.hasTitle && !this.labelText){
                var labelId = this.template.querySelector('.nhsuk-label--m').id;
                this.template.querySelector('.nhsuk-fieldset').setAttribute('aria-labelledby', labelId);
            }
        }

        if(this.hasHintLabel){
            var hintId = this.template.querySelector('.nhsuk-select-hint-label').id;
            var radiogroupElement = this.template.querySelector('.nhsuk-fieldset');
            var getAriadescribedbyId = radiogroupElement.getAttribute('aria-describedby');
            var ariadescribedbyId = getAriadescribedbyId == null ? hintId : getAriadescribedbyId.includes(hintId) ? getAriadescribedbyId :  hintId + ' ' + getAriadescribedbyId;
            this.template.querySelector('.nhsuk-fieldset').setAttribute('aria-describedby', ariadescribedbyId);
        }
        
        if(this.hasHint1 && !this.hasHintLabel){
            var hintId = this.template.querySelector('.nhsuk-select-hint').id;
            var radiogroupElement = this.template.querySelector('.nhsuk-fieldset');
            var getAriadescribedbyId = radiogroupElement.getAttribute('aria-describedby');
            var ariadescribedbyId = getAriadescribedbyId == null ? hintId : getAriadescribedbyId.includes(hintId) ? getAriadescribedbyId :  hintId + ' ' + getAriadescribedbyId;
            this.template.querySelector('.nhsuk-fieldset').setAttribute('aria-describedby', ariadescribedbyId);
        }
        
        if(this.selectedRadio) {
            var inputElements = this.template.querySelectorAll('.nhsuk-select-radios__input');
            for(let i = 0; i < this.radioOptions.length; i++) {
                if(this.radioOptions[i].value === this.selectedRadio) {
                    if(inputElements[i].getAttribute('aria-expanded')){
                        inputElements[i].setAttribute('aria-expanded', "true");
                        if(inputElements[i].getAttribute('aria-controls')){
                            var id = inputElements[i].getAttribute('data-ref-id');
                            var element = this.template.querySelector(`[data-id="${id}"]`);
                            element.classList.contains('nhsuk-radios__conditional--hidden') ? 
                                element.classList.remove('nhsuk-radios__conditional--hidden') : null;
                        }
                    }
                }
            }
        }
    }

    disconnectedCallback(){
        this.unsubscribe();
        this.unsubscribeScrollTo();
        this.handleLWCConnectionUnsubscribe();
    }

    handleSubscribe() {
        if (this.isSubscribedToValidationRequestEvent) return;
        registerListener(FLOW_VALIDATION_REQ_EVENT_NAME, this.handleValidationRequestHandler = (message) => {
            if(message.requestValidation){               
                this.isComponentValid();
            }
        }, this);
        this.isSubscribedToValidationRequestEvent = true;
    }

    unsubscribe(){
        if (this.isSubscribedToValidationRequestEvent) {
            unregisterListener(FLOW_VALIDATION_REQ_EVENT_NAME, this.handleValidationRequestHandler, this);
            this.isSubscribedToValidationRequestEvent = false;
        }
    }

    subscribeScrollTo() {
        if (this.isSubscribedToScrollToEvent) return;
        registerListener(SCROLL_TO_EVENT_NAME, this.scrollToHandler = (message) => {
            if(message.targetId) {
                scrollToElement(this, message.targetId);
            }
        }, this);
        this.isSubscribedToScrollToEvent = true;
    }

    unsubscribeScrollTo() {
        if (this.isSubscribedToScrollToEvent) {
            unregisterListener(SCROLL_TO_EVENT_NAME, this.scrollToHandler, this);
            this.isSubscribedToScrollToEvent = false;
        }
    }  
    
    handleLWCConnectionSubscribe() {
        if (this.isSubscribedToConnectionRequestEvent) return;
        registerListener(DISPLAYELEMENT_INPUTELEMENT_CONNECTION, this.handleConnectionRequest = (message) => {
            if(message.identifier && message.identifier.includes(this.identifier)){              
                this.template.querySelector('.nhsuk-fieldset').setAttribute('aria-labelledby', message.identifier);
            }
        }, this);
        this.isSubscribedToConnectionRequestEvent = true;
    }

    handleLWCConnectionUnsubscribe(){
        if (this.isSubscribedToConnectionRequestEvent) {
            unregisterListener(DISPLAYELEMENT_INPUTELEMENT_CONNECTION, this.handleConnectionRequest, this);
            this.isSubscribedToConnectionRequestEvent = false;
        }
    }

    setDefaultValue(){
        // set the default value
        if(this.selectedRadio) {
            var inputElements = this.template.querySelectorAll('.nhsuk-select-radios__input');
            for(let i = 0; i < this.radioOptions.length; i++) {
                if(this.radioOptions[i].value === this.selectedRadio) {
                    this.selectedValue = this.radioOptions[i].value;
                    this.radioOptions[i].checked = true;
                    this.enteredTextLabel = this.radioOptions[i].inputLabel;

                    if(this.enteredValue){
                        this.enteredText = getSanitizedData(this.enteredValue);
                        if(this.radioOptions[i].type === 'phone'){
                            let result = this.enteredValue.replace(/[- )(]/g,'');
                            if(result.match(PHONE_REGEX)) {
                                this.errorShowPhone =  false; 
                                this.enteredText = result; 
                            }
                            else{
                                this.errorShowPhone =  true;
                            } 
                        }
                        if(this.radioOptions[i].type === 'internationalPhone'){
                            let result = this.enteredValue.replace(/[- )(]/g,'');
                            if(PhoneFormat.isValidNumber(result) && INDENTIFY_LETTERS.test(result)) {
                                this.errorShowInternationalPhone =  false;   
                                this.enteredText = result;
                            }
                            else{
                                this.errorShowInternationalPhone =  true;
                            } 
                        } 
                        else if(this.radioOptions[i].type === 'email'){
                            if(this.enteredValue.match(EMAIL_REGEX)) {
                                this.errorShowEmail =  false;   
                            }
                            else{
                                this.errorShowEmail =  true;
                            }
                        }
                        else if(this.radioOptions[i].type === 'number'){
                            this.invalidNumber = undefined;
                            this.isValidNumber(this.enteredValue);
                            if(!this.invalidNumber) {
                                this.errorShowNumber =  false;   
                            }
                            else{
                                this.errorShowNumber =  true;
                            }
                        }
                        else if(this.radioOptions[i].type === 'postcode'){
                            if(this.enteredValue.match(POST_CODE_REGEX)) {
                                this.errorShowEmail =  false;
                            }
                            else{
                                this.errorShowEmail =  true;
                            }
                        }
                    }
                    break;
                }
            }
        } 
    }

    updateValue(event){
        this.errorShowPhone = false; 
        this.errorShowInternationalPhone = false; 
        this.errorShowEmail = false; 
        this.errorShowNumber = false; 
        this.pageErrors = [];
        this.inputCssError = false;
        const updatedValue = event.target.value;
        var inputElements = this.template.querySelectorAll('.nhsuk-select-radios__input');
        inputElements.forEach(inputElement =>{
            if(inputElement.getAttribute('aria-expanded')){
                inputElement.setAttribute('aria-expanded', "false");
            }
        });
        var divElements = this.template.querySelectorAll('.nhsuk-select-radios__conditional');
        divElements.forEach(divElement =>{
            !divElement.classList.contains('nhsuk-radios__conditional--hidden') ? 
                divElement.classList.add('nhsuk-radios__conditional--hidden') : null;
            
        });

        this.radioOptions.forEach(option => {
            option.checked = option.value === updatedValue;
            
            if(option.value === updatedValue) {
                this.selectedValue = updatedValue;
                this.selectedOptionType = option.type
                const attributeChangeEvent = FlowAttributeChangeEvent('selectedRadio', updatedValue);
                this.dispatchEvent(attributeChangeEvent);
                this.enteredTextLabel = option.inputLabel;
                if(event.target.getAttribute('aria-expanded')){
                    event.target.setAttribute('aria-expanded', "true");
                }
                if(event.target.getAttribute('aria-controls')){
                    var id = event.target.getAttribute('data-ref-id');
                    var element = this.template.querySelector(`[data-id="${id}"]`);
                    element.classList.contains('nhsuk-radios__conditional--hidden') ? 
                        element.classList.remove('nhsuk-radios__conditional--hidden') : null;
                }
            }
        })
        this.enteredText = null;
        const attributeChangeEventUpdate = FlowAttributeChangeEvent('enteredValue', this.enteredText);
        this.dispatchEvent(attributeChangeEventUpdate);
    }

    // Related to child component, this will make child components errors visible on radio buttons
    dateInputError(event){
        this.pageErrors.push({key: 1, target: PAGE_ERROR_RADIO_TYPE, detail: event.detail})
    }

    dateValueChanged(event){
        this.enteredText = event.detail;
        const attributeChangeEventText = FlowAttributeChangeEvent('enteredValue', this.enteredText);
        this.dispatchEvent(attributeChangeEventText);
    }

    // get the entered text and send it to the flow
    textChange(event){
        let textVal = getSanitizedData(event.target.value);
        for(let i = 0; i < this.radioOptions.length; i++) {
            if(this.radioOptions[i].label === event.target.name){
                this.enteredText = textVal;
                if(this.radioOptions[i].inputLabel){
                    this.enteredTextLabel = this.radioOptions[i].inputLabel;
                }
                if(this.radioOptions[i].type === 'phone'){
                    let result = textVal.replace(/[- )(]/g,'');
                    if(result.match(PHONE_REGEX)) {
                        this.errorShowPhone =  false;   
                        this.enteredText = result;
                    }
                    else{
                        this.errorShowPhone =  true;
                    } 
                } 
                if(this.radioOptions[i].type === 'internationalPhone'){
                    let result = textVal.replace(/[- )(]/g,'');
                    if(PhoneFormat.isValidNumber(result) && INDENTIFY_LETTERS.test(result)) {
                        this.errorShowInternationalPhone =  false;   
                        this.enteredText = result;
                    }
                    else{
                        this.errorShowInternationalPhone =  true;
                    } 
                } 
                else if(this.radioOptions[i].type === 'email'){
                    if(textVal.match(EMAIL_REGEX)) {
                        this.errorShowEmail =  false;   
                        this.enteredText = textVal;
                    }
                    else{
                        this.errorShowEmail =  true;
                    }
                }
                else if(this.radioOptions[i].type === 'number'){
                    this.invalidNumber = undefined;
                    this.isValidNumber(textVal);
                    if(!this.invalidNumber) {
                        this.errorShowNumber =  false;   
                        this.enteredText = textVal;
                    }
                    else{
                        this.errorShowNumber =  true;
                    }
                }
                else if(this.radioOptions[i].type === 'postcode'){
                     if(textVal.match(POST_CODE_REGEX)) {
                        this.errorShowPostCode =  false;
                        this.enteredText = textVal;
                    }
                    else{
                        this.errorShowPostCode =  true;
                    }
                }
            }
        }
        const attributeChangeEventText = FlowAttributeChangeEvent('enteredValue', this.enteredText);
        this.dispatchEvent(attributeChangeEventText);
    }

    parseOptionList(){
        this.radioOptions = [];
        let hintList = [];
        const optionList = this.customOptionList.split(BULLET_LIST_DELIMITER);
        let optionTypeList = [];
        let optionInputLabelList = [];
        if(this.customOptionTypeList != null && this.customOptionTypeList != '' 
        && this.customOptionTypeList != 'undefined'){
            optionTypeList = this.customOptionTypeList.split(BULLET_LIST_DELIMITER);
        }
        if(this.customOptionInputLabelList != null && this.customOptionInputLabelList != '' 
        && this.customOptionInputLabelList != 'undefined'){
            optionInputLabelList = this.customOptionInputLabelList.split(BULLET_LIST_DELIMITER);
        }
        if(this.customHintsList !== undefined && this.customHintsList !== '' && this.customHintsList !== null){                    
            hintList = this.customHintsList.split(BULLET_LIST_DELIMITER);
        }

        for(let i = 0; i < optionList.length; i++){
            let optionValue = {};
            var optionValueId = `option-value-${optionList[i]}`;
            optionValue.key = optionValueId.replace(/\s+/g, '-').replaceAll(' ','-').replaceAll('&','').replaceAll(')','').replaceAll('(','').replaceAll(',','');

            //optionValue.key = `option-value-${optionList[i].replace(/\s+/g, '-')}`;
            optionValue.radioInputName = `radio-input-${this.titleText}`;
            optionValue.value = optionList[i];
            optionValue.label = optionList[i];
            optionValue.checked = false;
            // This is used to render child component for date input
            optionValue.isNHSDate = false;

            if(hintList.length > 0){
                optionValue.hint = hintList[i];
                optionValue.hintId = hintList[i].replace(/\s+/g, '-');
            }
            if(optionTypeList.length > 0){
                optionValue.type = optionTypeList[i];
                optionValue.isNHSDate = optionTypeList[i] === 'nhsdate';
            }
            if(optionInputLabelList.length > 0 && optionInputLabelList[i]){
                optionValue.inputLabel = optionInputLabelList[i];
                optionValue.inputLabelId = optionInputLabelList[i].replace(/\s+/g, '-');
                optionValue.conditionalDivId = optionInputLabelList[i].replace(/\s+/g, '-') + '-' + i;
            }
            this.radioOptions.push(optionValue);
        }

        this.setDefaultValue();
    }

    get getGridClass() {
        return getGridSize();
    }

    get hasTitle() {
        return (this.titleText !== undefined && this.titleText !== '' && this.titleText !== null);
    }

    get hasHint1() {
        return (this.hint1Text !== undefined && this.hint1Text !== '' && this.hint1Text !== null);
    }

    get hasHint2() {
        return (this.hint2Text !== undefined && this.hint2Text !== '' && this.hint2Text !== null);
    }  

    get hasHints() {
        return (this.useHints || (this.customHintsList !== undefined && this.customHintsList !== '' && this.customHintsList !== null));
    }  

    get radiosClass() {
        return RADIO_CSS_STANDARD;
    } 

    //dynamic width of the input field
    get inputWidthClass() {
        let inputCss;
        if(this.inputWidth){
            inputCss = INPUT_WIDTH_CSS_STANDARD + this.inputWidth;
        }
        else{
            inputCss = INPUT_CSS_STANDARD;
        }    
        if(this.inputCssError){
            inputCss = inputCss + ' ' + INPUT_CSS_STANDARD_INVALID;
        }
        else{
            inputCss = inputCss + ' ' + INPUT_CSS_STANDARD;
        }
        return inputCss;
    }

    get formGroupErrorClass() {
        if(this.radiosGenericErrorDetail) {
            return FORM_GROUP_CSS_STANDARD_ERROR;
        }
        return FORM_GROUP_CSS_STANDARD;
    }

    get radiosClassErrorDetail() {
        if(this.pageErrors && this.pageErrors.length > 0) {
            for (let i = 0; i < this.pageErrors.length; i++) {
                const pageError = this.pageErrors[i];
                if (pageError.target === PAGE_ERROR_RADIO_TYPE) {
                    return pageError.detail;
                }
            }
        }
        return undefined;
    } 
    
    isComponentValid(){
        this.pageErrors = [];
        this.radiosGenericErrorDetail = undefined;
        const payload = {
            source: 'Component',
            isValid: true,
            errorMessage: null
        };

        // Main validation for date is done on child component
        if(this.selectedOptionType === 'nhsdate') return;

        if(!this.selectedValue && this.requiredField){
            var element = this.template.querySelector('.nhsuk-radios');
            var inputElement = this.template.querySelector('.nhsuk-radios__input');
            console.log('radio Id = ' + inputElement.id);

            payload.isValid = false;
            //payload.errorMessage = {key: 1, target: element.id, detail: this.customErrorMessage};
            payload.errorMessage = {key: 1, target: inputElement.id, detail: this.customErrorMessage};
            
            this.pageErrors = [];
            this.radiosGenericErrorDetail = this.customErrorMessage;
        } 
        if((this.enteredText === null || this.enteredText === '') && this.enteredTextLabel){
            this.inputCssError = true;
            var prefix = this.selectedOptionType === 'postcode' ? 'Enter a ' : 'Enter your ';
            var dynamicErrorMessage = prefix + this.enteredTextLabel.toLowerCase();
            var element = this.template.querySelector('.nhsuk-input');
            payload.isValid = false;
            payload.errorMessage = {key: 1, target: element.id, detail: dynamicErrorMessage};
            this.pageErrors = [];
            this.pageErrors.push({key: 1, target: PAGE_ERROR_RADIO_TYPE, detail: dynamicErrorMessage})
        }
				
				if(this.enteredText!=null){
            if(this.enteredText.length > 11 && this.customOptionInputLabelList.includes('barcode')){
                this.inputCssError = true;
                var dynamicErrorMessage = 'Enter a valid ' + this.enteredTextLabel.toLowerCase(); 
                var element = this.template.querySelector('.nhsuk-input');
                payload.isValid = false;
                payload.errorMessage = {key: element.id, target: element.id, detail: 'Your test barcode number must not be more than 11 characters'};
                this.pageErrors = [];
                this.pageErrors.push({key: 1, target: PAGE_ERROR_RADIO_TYPE, detail: 'Your test barcode number must not be more than 11 characters'});
						}
            if(this.enteredText.length > 12 && this.enteredTextLabel.includes('Booking')){
                this.inputCssError = true;
                var dynamicErrorMessage = 'Enter a valid ' + this.enteredTextLabel.toLowerCase(); 
                var element = this.template.querySelector('.nhsuk-input');
                payload.isValid = false;
                payload.errorMessage = {key: element.id, target: element.id, detail: ERROR_MESSAGE_CHARACTER_LIMIT};
                this.pageErrors = [];
                this.pageErrors.push({key: 1, target: PAGE_ERROR_RADIO_TYPE, detail: ERROR_MESSAGE_CHARACTER_LIMIT});
            }
        }
        
        
       if(this.enteredText!=null){
            
        if(this.enteredText.includes('@') || this.enteredText.includes('£') || this.enteredText.includes('!') || this.enteredText.includes('*') || this.enteredText.includes('$') || this.enteredText.includes('%') || this.enteredText.includes('&') || this.enteredText.includes('(') || this.enteredText.includes(')') || this.enteredText.includes('-') || this.enteredText.includes('/') || this.enteredText.includes(';') || this.enteredText.includes(':') && (this.customOptionInputLabelList.includes('Booking') || this.customOptionInputLabelList.includes('barcode'))){
            this.inputCssError = true;
            var dynamicErrorMessage = 'Enter a valid ' + this.enteredTextLabel.toLowerCase();
            var element = this.template.querySelector('.nhsuk-input');
            payload.isValid = false;
            payload.errorMessage = {key: element.id, target: element.id, detail: ERROR_MESSAGE_PROHIBITED};
            this.pageErrors = [];
            this.pageErrors.push({key: 1, target: PAGE_ERROR_RADIO_TYPE, detail: ERROR_MESSAGE_PROHIBITED})
        }
    }
    if(this.errorShowPhone && this.enteredTextLabel){
            this.inputCssError = true;
            var dynamicErrorMessage = 'Enter ' + (this.enteredTextLabel.match(VOWEL_REGEX) ? 'an ': 'a ') + this.enteredTextLabel.toLowerCase() + INVALID_PHONE; 
            var element = this.template.querySelector('.nhsuk-input');
            payload.isValid = false;
            payload.errorMessage = {key: element.id, target: element.id, detail: dynamicErrorMessage};
            this.pageErrors = [];
            this.pageErrors.push({key: 1, target: PAGE_ERROR_RADIO_TYPE, detail: dynamicErrorMessage})
        }
        if(this.errorShowInternationalPhone && this.enteredTextLabel){
            this.inputCssError = true;
            var dynamicErrorMessage = 'Enter a valid ' + this.enteredTextLabel.toLowerCase(); 
            var element = this.template.querySelector('.nhsuk-input');
            payload.isValid = false;
            payload.errorMessage = {key: element.id, target: element.id, detail: dynamicErrorMessage};
            this.pageErrors = [];
            this.pageErrors.push({key: 1, target: PAGE_ERROR_RADIO_TYPE, detail: dynamicErrorMessage})
        }
        if(this.errorShowEmail && this.enteredTextLabel){
            this.inputCssError = true;
            var dynamicErrorMessage = 'Enter ' + (this.enteredTextLabel.match(VOWEL_REGEX) ? 'an ': 'a ') + this.enteredTextLabel.toLowerCase() + INVALID_EMAIL; 
            var element = this.template.querySelector('.nhsuk-input');
            payload.isValid = false;
            payload.errorMessage = {key: element.id, target: element.id, detail: dynamicErrorMessage};
            this.pageErrors = [];
            this.pageErrors.push({key: 2, target: PAGE_ERROR_RADIO_TYPE, detail: dynamicErrorMessage})         
        }
        if(this.errorShowNumber && this.enteredTextLabel){
            this.inputCssError = true;
            var element = this.template.querySelector('.nhsuk-input');
            payload.isValid = false;
            payload.errorMessage = {key: element.id, target: element.id, detail: this.invalidNumber};
            this.pageErrors = [];
            this.pageErrors.push({key: 2, target: PAGE_ERROR_RADIO_TYPE, detail: this.invalidNumber})         
        }
        if(this.errorShowPostCode && this.enteredTextLabel){
            this.inputCssError = true;
            var element = this.template.querySelector('.nhsuk-input');
            payload.isValid = false;
            payload.errorMessage = {key: element.id, target: element.id, detail: INVALID_POSTCODE};
            this.pageErrors = [];
            this.pageErrors.push({key: 2, target: PAGE_ERROR_RADIO_TYPE, detail: INVALID_POSTCODE})
        }
        else {
            
            this.inputCssError = false;
            this.selectedRadio = this.selectedValue;
            if(this.enteredText){
                this.enteredValue = this.enteredText;
            }    
            if(this.requiredInSummary){
                FlowContextProvider.addSummaryItem({
                    sortOrder : this.sortOrderNumber,
                    label : this.labelForSummary,
                    value : this.selectedRadio,
                    dependentLabel : this.dependentLabelForSummary,
                    dependentValue : this.dependentValueForSummary
                });
            }            
        }
        fireEvent(this.pageRef, FLOW_VALIDATION_RESP_EVENT_NAME, payload);
    }
    
    isValidNumber(enteredNumber){
        if(!this.fieldNameErrorLabel){
            this.fieldNameErrorLabel = 'value';
        }    
        if(!enteredNumber.match(NUMBER_REGEX)) {
            this.invalidNumber = this.numberExampleForError 
                ? this.fieldNameErrorLabel + ' must be a number, like ' + this.numberExampleForError 
                : this.fieldNameErrorLabel + ' must be a number'; 
        } else {
            if((this.minChar > enteredNumber.length || enteredNumber.length > this.maxChar) &&
                (this.minChar && this.maxChar)){
                if(this.minChar == this.maxChar){
                    this.invalidNumber = this.fieldNameErrorLabel + ' must be ' + this.minChar + ' digits';
                } else {
                    this.invalidNumber = this.fieldNameErrorLabel + ' must be between ' + this.minChar + ' and ' + this.maxChar + ' digits';
                }                
            } else if(this.minChar > enteredNumber.length){
                this.invalidNumber = this.fieldNameErrorLabel + ' must be ' + this.minChar + ' digits or more';
            } else if(enteredNumber.length > this.maxChar && this.maxChar){
                this.invalidNumber = this.fieldNameErrorLabel + ' must be ' + this.maxChar + ' digits or fewer';
            } else {
                this.invalidNumber = false; 
            }                        
        }       
    }
    
}
Editor is loading...