0

我有一个以“选择位置”选项开头的选择字段,并希望强制用户在提交之前选择某些内容。我看到了这篇关于在选项可用之前禁用提交按钮的文章amp-bind,但如果可能的话,我想使用 amp-form 内置的验证。

我尝试在and字段上使用该pattern属性。我使用了类似的东西和多种变体,但没有任何成功。<select><option>pattern="^((?!default).)*$"

<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>

当我单击提交而不更改值时,我希望会出现验证错误,但事实并非如此。是否可以将此验证方法与 Select 字段一起使用?还是我只需要使用前面提到的 amp-bind 方法?

4

1 回答 1

1

我假设您已经从表单中添加了所有必需的脚本 js 文件。我提供了一个评级示例。

AMP 提供两种类型的验证,一种用于空白值,另一种用于模式不匹配时。您缺少空白值验证。

<script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>


<form action-xhr="here will be your url" custom-validation-reporting="show-all-on-submit" target="_top" method="post" class="wpcf7-form i-amphtml-form amp-form-dirty" novalidate="">

    <label for="rating">Select rating</label>
    <select name="rating" required="" class="user-invalid valueMissing" id="show-all-on-submit-select" aria-invalid="false">
        <option value="">Rate…&lt;/option>
        <option value="5">Perfect</option>
        <option value="4">Good</option>
        <option value="3">Average</option>
        <option value="2">Not that bad</option>
        <option value="1">Very poor</option>
    </select>
    // You are missing this one 
    <span visible-when-invalid="valueMissing" validation-for="show-all-on-submit-select">

         Please select rating..!!
    </span>
    // This is for the pattern validation message. If the field is having the value but not does not match with patter this span will provide the validation
    <span visible-when-invalid="patternMismatch" validation-for="show-all-on-submit-select">
            Please select rating..!!
    </span>

    <input type="submit" name="submit" value="Submit" class="wpcf7-form-control wpcf7-submit button yellow-button">

</form>

现在,如果您需要在代码中使用相同的解决方案,只需将其放在 span 下面,我认为它一定适合您:

 <span
    visible-when-invalid="valueMissing"
    required
    validation-for="formLocation" 
    validation-for="show-all-on-submit-select">
    Please Choose a Location
 </span>

谢谢

于 2020-06-06T19:54:09.883 回答