0

How can I get "/ˆ[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$/" in the Controller class?

                        <label for="clientEmail">E-mail</label>
                        <lightning:input name="clientEmail"
                                         type="email"
                                         pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$" 
                                         aura:id="clientEmail"
                                         required="false" 
                                         value="{!v.clientEmail}"
                                         label="E-mail" 
                                         variant="label-hidden"
                                         maxlength="60" />

I tried:

let rgxEmail= "/ˆ" + cmp.find(clientEmail).get("v.pattern") +"/";
if (!(rgxEmail.test(valueEmail))) {
            let errorMsg = "Invalid email" + "\n";
 }

But it's not working...

1 Answer 1

1

/pattern/ is only for literal regular expressions in source code. Do not use /pattern/ in the pattern attribute, nor when using the test method.

The pattern should be:

pattern="^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$" 

And in your code:

let emailRegex = new RegExp(cmp.find(clientEmail).get('v.pattern'));
if(!emailRegex.test(valueEmail)) {

Note that String.prototype.test doesn't exist, which is why you're having a problem doing that, you should be constructing a new RegExp object.

Also, it's not normally necessary to do that, you can use the built-in validation logic:

let emailInput = cmp.find(clientEmail);
if(!emailInput.checkValidity()) {
  emailInput.reportValidity();
}

This is outlined in the documentation. Here's how they recommend checking all fields:

    var allValid = component.find('contact').reduce(function (validSoFar, inputCmp) {
        inputCmp.reportValidity();
        return validSoFar && inputCmp.checkValidity();
    }, true);

    if (allValid) {
      // continue, all fields are valid
    }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .