Salesforce LWC learning (sixteen) Validity in the use of form

This reference:

https://developer.salesforce.com/docs/component-library/bundle/lightning-input/documentation

https://www.lightningdesignsystem.com/components/input/#Error

When we have form operations on the front end or a large number of input conditions as search conditions, there are usually some checks, such as non-null check, type check, etc. For salesforce lwc or aura, there are usually front-end verifications in the following situations.

  • badInput: used to determine whether the current input content is a legal value;
  • patternMismatch: used to determine whether the current input content meets the specified pattern;
  • rangeOverflow: judge whether the input content is too large for the number-related types and exceeds the default maximum value;
  • rangeUnderflow: judge whether the value of the input content is too small and less than the default minimum value for the type related to the number;
  • stepMismatch: For the types related to numbers, after using the up or down buttons in the input box, we can add or subtract the content of the related input box according to the value set by step. Will report an error stepMismatch;
  • tooLong: Specifies whether the length of value exceeds the currently set maxlength;
  • tooShort: Specifies whether the length of value is less than the currently set minlength;
  • typeMismatch: for url or email type variables, used to determine whether the currently entered value type matches;
  • valueMissing: This type of error will be reported if there is no value in the required field.

When this situation occurs in the verification of the form, the relevant default error message will be displayed.

  • badInput: Enter a valid value.
  • patternMismatch: Your entry does not match the allowed pattern.
  • rangeOverflow: The number is too high.
  • rangeUnderflow: The number is too low.
  • stepMismatch: Your entry isn't a valid increment.
  • tooLong: Your entry is too long.
  • tooShort: Your entry is too short.
  • typeMismatch: You have entered an invalid format.
  • valueMissing: Complete this field.

We are probably familiar with the following picture, and often see the default display information similar to when the input box is not satisfied. You can get a better understanding of some of the above information through the following figure.

The effect of the red mark in the screenshot above is the validity of this article. The use of validity can enable users to better position and achieve a better user experience when a large number of input operations are not satisfied.

See the reference link above for the CSS implementation style of the red operation. What we consider more in this article is how to use it.

Most of the in-force selection tags in the form form have built-in checkValidity / reportValidity / setCustomValidity or similar functions. Such as input / combobox and other tags. checkValidity is used to verify whether the elements of the current form meet the requirements, and reportValidity is used to display the effect based on checkValidity. If the current element meets the requirements, the error message is cleared and return true; if the current element does not meet the requirements, the error message is displayed and return false.

let allValid = [...this.template.querySelectorAll('lightning-input')]
            .reduce((validSoFar, inputFields) => {
                inputFields.reportValidity();
                return validSoFar && inputFields.checkValidity();
            }, true);

We analyze the above code:

  1. Get the lighting-input in the current component through querySelectorAll;
  2. Use the reportValidity method to verify each lighting-input element. If the current element meets the requirements, it returns true, if it does not meet the requirements, it returns false and the element displays the wrong default information according to the wrong type;
  3. Use checkValidity to confirm whether the current element conforms, returns true if it matches, and returns false if it does not.

It should be noted that when the form is submitted, if there are non-conforming elements on the page, it will not block your form submission. So if we see a similar prompt above before the page is submitted, don't take it lightly, you need to check before save, if you want to save logic successfully, you need to return and reportValidity ().

Through the above demo, we can see that querySelectorAll is used to traverse all lightning-input elements for reportValidity and checkValidity. This method can only traverse all elements in the current component. If the component contains subcomponents, the subcomponent contains input and other similar elements, and the subcomponents cannot be verified. Experiment with a demo.

testSonInputComponent.html: only used to display an input box

<template>
    <lightning-input label="test son" required></lightning-input>
</template>

testParentInputComponent.html: introduce testSonInputComponent and put an input component

<template>
    <lightning-layout multiple-rows="true">
        <lightning-layout-item size="6">
            <lightning-input label="test parent" type="text" required></lightning-input><br/>
        </lightning-layout-item>
        <lightning-layout-item size="6">
            <c-test-son-input-component></c-test-son-input-component>
        </lightning-layout-item>
        <lightning-layout-item>
            <lightning-button label="validity" onclick={checkInputValidity}></lightning-button>
        </lightning-layout-item>
    </lightning-layout>
</template>

testParentInputComponent.js: Iterate over all input tags and perform reportValidity operation.

import { LightningElement } from 'lwc';

export default class TestParentInputComponent extends LightningElement {
    checkInputValidity() {
        let allValid = [...this.template.querySelectorAll('lightning-input')]
            .reduce((validSoFar, inputFields) => {
                inputFields.reportValidity();
                return validSoFar && inputFields.checkValidity();
            }, true);
        console.log('result : ' + allValid);
    }
}

Effect display: When no tags are input, only the tags in the current component will be verified, and the sub-component tags will not be verified.

 If you want to verify, the currently thought of method is to call the sub-component for the parent component, which can make up for the verification function of the related sub-component, but can not pass the result of checkValidity. If you want to view allValid, you can only set the allValid variable manually based on whether there is a value in the parent component. The code is simply modified as follows:

testInputSonComponent.js: api tag declaration of the method, only after the declaration of the parent component can be called.

import { LightningElement, api } from 'lwc';

export default class TestSonInputComponent extends LightningElement {
    @api
    checkInputValidity() {
        let allValid = [...this.template.querySelectorAll('lightning-input')]
            .reduce((validSoFar, inputFields) => {
                inputFields.reportValidity();
                return validSoFar && inputFields.checkValidity();
            }, true);
    }
}

testInputParentComponent.js: Get the subcomponent through querySelector, and then call the subcomponent method.

import { LightningElement } from 'lwc';

export default class TestParentInputComponent extends LightningElement {
    checkInputValidity() {
        let allValid = [...this.template.querySelectorAll('lightning-input')]
            .reduce((validSoFar, inputFields) => {
                inputFields.reportValidity();
                return validSoFar && inputFields.checkValidity();
            }, true);
        
        this.template.querySelector('c-test-son-input-component').checkInputValidity();
        console.log('result : '+ allValid);
    }
}

Show results:

 One of the biggest problems with this approach is that the validity of the child component cannot be passed to the parent component. In the project, according to whether the value of the child component is empty, verify in the parent component and then set the value of allValid. In addition to this, there is no good way to think, and familiar partners can give better solutions.

In addition to the standard prompt information, lwc provides us with a custom error message method, namely setCustomValidity. This method has a similar method in many methods. It is used when the standard prompt information does not meet the requirements or a custom check if you want to display the custom prompt information. When using setCustomValidity, combined with reportValidity, you can display a custom error scene prompt.

Continue to transform the code. Customize the prompt when the content of the input box is less than 2 characters.

import { LightningElement } from 'lwc';

export default class TestParentInputComponent extends LightningElement {
    checkInputValidity() {
        let allValid = [...this.template.querySelectorAll('lightning-input')]
            .reduce((validSoFar, inputFields) => {
                

                if(inputFields.value.length < 2) {
                    console.log('execute');
                    inputFields.setCustomValidity('输入的长度应该超过2');
                }
                inputFields.reportValidity();
                return validSoFar && inputFields.checkValidity();
            }, true);
        
        this.template.querySelector('c-test-son-input-component').checkInputValidity();
        

        console.log('result : ' + allValid);
    }
}

Results show:

 Summary: The article briefly introduces the simple and practical of Validity. There is no particularly good solution for how to adapt the subcomponents better. Friends who have good ideas leave a message. There are welcome messages that you do n’t understand, and welcome errors if you have errors.

Guess you like

Origin www.cnblogs.com/zero-zyq/p/12734982.html