LoginSignup
3
3

More than 5 years have passed since last update.

入力チェックエラーの表示について

Posted at

入力チェックエラーの表示について

画面で入力チェックを行った際に、エラーメッセージ表示します。
表示にはデフォルトの「ui:inputDefaultError」を使用します。
ui:inputDefaultErrorは画面にタグを入れる必要なく、使用することができます。

AdventCalendarCmp.cmp
<aura:component controller="TLP.AdventCal">

        <aura:attribute name="child" type="TLP.ChildObj__c"
             default="{ 'sobjectType': 'TLP__ChildObj__c',
                         'Name': '',
                         'TLP__Parent__c': 'a0Ci000000LubnS'}"/>

        <ui:inputText aura:id="parentId" label="parentId"
                      value="{!v.child.TLP__Parent__c}" 
                      class="form-control"  
                      placeholder="id"/>

        <ui:inputText aura:id="childName" label="名前"  
                  value="{!v.child.Name}" 
                  class="form-control" 
                  placeholder="名前を登録してください"/>

        <ui:button label="button" press="{!c.callApex}"/>    
</aura:component>

javascriptのコントローラに入力チェック処理を書きます。
入力チェック時にメッセージを追加する項目には、addError関数を使って、エラーメッセージを追加します。
赤く反転させる項目には、setValid関数を使用し、falseを設定します。

エラーのイメージ
Aura 2.jpg

入力チェックでエラーとならないケースでは、ちゃんとsetValid関数を使ってtrueを設定する必要があります。
trueに設定しないと、正しく入力しても赤く反転された項目が赤のままとなります。

AdventCalendarCmpController.js
        callApex :function(component, event, helper){    
        var nameInput,nameInputValue,parentIdInput;
        nameInput = component.find("childName");
        parentIdInput = component.find("parentId");
        nameInputValue = nameInput.get("v.value");

        if($A.util.isEmpty(nameInputValue)){            
            nameInput.setValid("v.value",false);
            parentIdInput.setValid("v.value",false);

            nameInput.addErrors('v.value',[{message:"必ず入力してください"}]);
            parentIdInput.addErrors('v.value',[{message:"こちらも入力は必須です"}]);
            console.log('error!');
        }else{
            component.setValid("v.child.Name",true);
            parentIdInput.setValid("v.value",true);
            helper.registerName(component);
        }

こんな感じで、ApexのAction呼び出し後のcallbackでもかけるので、チェックした内容を元に、エラーを表示することも可能です。

    registerName : function(component) {
        var action = component.get('c.registerChild');

        action.setParams({
            'child':component.get("v.child")
        });

        action.setCallback(this,function(a){
            if(a.error && a.error.length){
                var childNameInput = component.find("childName");
                childNameInput.setValid('v.value',false);
                childNameInput.addErrors('v.value',[{message:"callbackでもエラーをかける"}]);
            }
        });

        $A.enqueueAction(action);
    },
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3