Yura
Yura

Reputation: 125

HTML5 - Pattern attribute can't be used in input element

I'm currently having an input element for a phone number and trying to use the pattern attribute but it refuses to do so. it says "Validation(HTML5): Pattern is not a valid attribute of element input"! When I change the type to "text" it says that pattern attribute is only valid when title is present!

<input type="number" class="form-control"data-require="" id="Mobile" placeholder="Mobile No" autocomplete="off" pattern="[\+]\d{3}d{9}" required>

UPDATE:

I Added title attribute and it's working now! but my only issue is that when i click submit, it submits the form even though that the format is not matching.

Upvotes: 4

Views: 2384

Answers (3)

Yura
Yura

Reputation: 125

It's fixed, just added this in my javascript.

/[+]\d{3}d{9}/.test(PhoneNo)

Upvotes: 0

Sebastian Brosch
Sebastian Brosch

Reputation: 43574

The <input> should be valid without the title attribute (validated on https://validator.nu/):

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
  </head>
  <body>
    <input type="text" class="form-control" data-require="" id="Mobile" placeholder="Mobile No" autocomplete="off" pattern="[\+]\d{3}d{9}" required>
  </body>
</html>

Additional changes:

  • A space is missing before attribute data-require.
  • The pattern attribute is only allowed on the following types: email, password, search, tel, text, or url.

Your regular expression ([\+]\d{3}d{9}) is also invalid. You can try one of the following rules:

  • [\+]\d{3}\d{9}
  • [\+]\d{12}

You are missing the \ before the second d to match only numbers. The second pattern is a minified version of the first pattern.

Upvotes: 5

Rasovica
Rasovica

Reputation: 229

You can add oninvalid attribute to the tag

<input type="text" name="HasAPattern" pattern="\w{3}" title="Enter 3 characters" oninvalid="setCustomValidity('Needs to match patern')" >

The HTMLSelectElement.setCustomValidity() method sets the custom validity message for the selection element to the specified message. Use the empty string to indicate that the element does not have a custom validity error.

You can also use code like event.preventDefault(); inside it to cancel the submit if invalid

Upvotes: -1

Related Questions