+ Start a Discussion
Balu Phrabha123Balu Phrabha123 

How to make required field on Lead creation LWC

HI All, 

I want to make phone required when i click the create lead button.
But the lead is creating without phone. And also i need to show when phone is empty show tost message.  

Below is my code and it is not working. 

HTML:
<div class="slds-col slds-size_2-of-7">
<lightning-input-field class="Phone" required field-name="Phone"
value={leadphone}>
</lightning-input-field>
</div>

Js.code
handleSubmit(event) {
        this.createlabel = "Creating Lead...";
        event.preventDefault();
        const fields = event.detail.fields;   // stop the form from submitting
        if (this.template.querySelector('.Phone') === '') {
            this.fieldvalidationerror();
        } else {
            this.template.querySelector('lightning-record-edit-form').submit(fields);
        }
    }

//Tost Message
fieldvalidationerror() {
const event = new ShowToastEvent({
mode: 'dismissable',
variant: 'error',
title: 'We hit a snag!',
message: 'Please fill required fields'
});
this.dispatchEvent(event);
}User-added image
 
David Zhu 🔥David Zhu 🔥
You may need to change this line:
if (this.template.querySelector('.Phone') === '') {

this.template.querySelector('.Phone') gets the DOM object for phone. It should be checking the value of the DOM object.

if (this.template.querySelector('.Phone').value.trim() == "" {
David Zhu 🔥David Zhu 🔥
Please try:
if ( this.template.querySelector('.Phone').value== undefined || this.template.querySelector('.Phone').value.trim()== "" || ) {
Jitendra Singh ShahiJitendra Singh Shahi

Hi, 

you can try this:

 

if(this.template.querySelector('.Phone') && this.template.querySelector('.Phone').value==null){
   alert('null error');
}else if(this.template.querySelector('.Phone').value.trim()==""){
   alert('empty val error');
}

If the above suggestion worked, let us know by marking the answer as "Best Answer" right under the comment which will help the rest of the community should they have a similar issue in the future.