I have a select field that starts with an option that says "Select Location" and want to force the user to choose something before submitting. I saw this article about disabling the Submit button with amp-bind
until an option is available, but I would like to use the validation built into amp-form if at all possible.
I have tried using the pattern
attribute on the <select>
and <option>
fields. I have used something similar to pattern="^((?!default).)*$"
and multiple variations without any success.
<form
id="contactForm"
method="post"
action-xhr="https://valid.json/endpoint"
custom-validation-reporting="show-all-on-submit"
target="_top">
[...]
<select
id="formLocation"
name="location_id"
pattern="^((?!default).)*$"
required>
<option value="default" disabled selected>Select Location</option>
<option value="newyork">New York</option>
<option value="losangeles">Los Angeles</option>
</select>
<span
visible-when-invalid="patternMismatch"
required
validation-for="formLocation">
Please Choose a Location
</span>
[...]
<input
id="formSubmit"
type="submit"
value="Submit">
</form>
When I click Submit without changing the value, I expect the validation error to appear, but it doesn't. Is it possible to use this validation method with Select fields? Or will I have to just use the aforementioned amp-bind method?
I am assuming that you have added all required script js files form the form. I have provided an example of the rating.
AMP is providing two types of validation one which is for the blank value and another when the pattern does not match. You are missing the blank value validation.
Now, If you need the same solution in your code just put below span I think it must work for you:
Thanks