Reputation: 125
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
Reputation: 125
It's fixed, just added this in my javascript.
/[+]\d{3}d{9}/.test(PhoneNo)
Upvotes: 0
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:
data-require
.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
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