Help me to undestand this lightning helper methods (reduce & showHelpMessageIfInvalid)?

I went through the lightning guide and try to learn the form controls, I got the below code which show that it validates the form fields, But would like to see more insight on

1 reduce – what this function will do

2) showHelpMessageIfInvalid – what this will do? Do we have some other methods like these? where we can see these documentation?

3) v.validity’- I don’t see this is used in any of the component – Help me to get clarified.

// Show error messages if required fields are blank
    var allValid = component.find('contactField').reduce(function (validFields,
    inputCmp) {
    inputCmp.showHelpMessageIfInvalid();
    return validFields && inputCmp.get('v.validity').valid;
    }, true);

Answer

1 reduce – what this function will do

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

Read here for more details:

var total = [0, 1, 2, 3].reduce(function(sum, value) {
  return sum + value;
}, 0);
// total is 6

reduce function is part of array prototype javascript object. It takes a function as input and applies that on the array and returns the output.

In this case the function does a summation of array members and returns the output.This is achieved by using reduce function which applies it on each and every member

2) showHelpMessageIfInvalid – what this will do? Do we have some other methods like these? where we can see these documentation?

This method is used by Lightning:Input tag to check for validity of input tag.

showHelpMessageIfInvalid(): Shows the help message if the form control is in an invalid state.

Lets take this input example:

   <lightning:input aura:id="field" label="Last name" placeholder="Last name" required="true" /> 

since required is marked true if user doesn’t enter any value the validity object for this input control will have value as valueMissing.

The other possible values are :

badInput: Indicates that the value is invalid

patternMismatch: Indicates that the value doesn’t match the specified pattern

rangeOverflow: Indicates that the value is greater than the specified max attribute

rangeUnderflow: Indicates that the value is less than the specified min attribute

stepMismatch: Indicates that the value doesn’t match the specified step attribute

tooLong: Indicates that the value exceeds the specified maxlength attribute

typeMismatch: Indicates that the value doesn’t match the required syntax for an email or url input type

valid: Indicates that the value is valid

valueMissing: Indicates that an empty value is provided when required attribute is set to true

when a form is submitted or field validity code is triggered. Below javascript code which is present in the same link runs and checks for validity of input components

({
    onClick: function (cmp, evt, helper) {
        var allValid = cmp.find('field').reduce(function (validSoFar, inputCmp) {
            inputCmp.showHelpMessageIfInvalid();
            return validSoFar && inputCmp.get('v.validity').valid;
         }, true);
         if (allValid) {
             alert('All form entries look valid. Ready to submit!');
         } else {
             alert('Please update the invalid form entries and try again.');
         }
     }
})

If you look at the above function reduce function is used again. just to break it down into smaller chunks to explain in detail

  1. Lets say you have 4 lightning:input components with id as ‘field’, component.find will return an array of 4 elements

  2. Array.reduce will run for each element and the function
    inputCmp.showHelpMessageIfInvalid(); will check if the element is
    valid if not it will show the help message and the red border to
    highlight the field is invalid.

  3. The third line 'return validSoFar && inputCmp.get('v.validity').valid;' is basically like an if and condition ,so in this case which is your third question(‘ v.validity’).valid checks if the component is in a valid state.
    v.validity is part of every lightning:input component to check for validity of the input component. Lets say that a lightning:input is marked required and user has not entered a value when this code runs it will return false which basically means the component is not valid.

  4. The return statement will return false even if one form component of your array fails for any of the invalidity status and overall allValid variable will become false.

  5. Finally the allValid will be false and an alert message will show in
    UI which indicates one more lightning:input tags are in invalid
    state. It means they have not entered data or they have not
    respected the fields formatter attribute etc.

Attribution
Source : Link , Question Author : bharath , Answer Author : RedDevil

Leave a Comment