如何删除“请匹配所请求的格式”提示信息

24

如何将"Please match the required format"更改为"Not valid"

我在Stackoverflow上找了很久都没有找到有用的内容,也许是重复问题,请帮帮我!

如果我在字段中键入'asd',然后按GO,然后继续输入消息,"Please match the required format"将出现

如果可能的话,我不想要混乱的代码,我希望它在html标签中!

<form id="banner-message">
    <input value=""
    name="email" 
    id="inputEmail"
    class="form-control"
    placeholder="email"
    required="" 
    autofocus=""  
    oninvalid="this.setCustomValidity('Not Valid')"                                               oninput="setCustomValidity('')"
    pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$">

    <button class="btn btn-lg  btn-block" type="submit">Go</button>
</form>


谢谢,但我确切地按照那里写的做了,但我无法使其工作。 - ThunderHorn
1
是的,但当我继续输入时,消息会显示。 - ThunderHorn
如果您输入例如“asd”,然后按“回车”,然后继续输入,它会显示“请匹配所需格式”。 - ThunderHorn
@KostadinSlavov 你正在使用哪个浏览器? - Chayim Friedman
铬和火狐 - ThunderHorn
似乎不再相关了..?我没有看到提示,只看到了预期的“无效”。 - phil294
5个回答

24
你需要使用 onchangethis.setCustomValidity

  <form id="banner-message">
      <input value="" 
      name="email" 
      id="inputEmail"
      class="form-control"
      placeholder="email"
      required=""
      autofocus="" 
      oninvalid="this.setCustomValidity('Not Valid')"
      onchange="try{setCustomValidity('')}catch(e){}"
      oninput="setCustomValidity(' ')"
      pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$">

      <button class="btn btn-lg  btn-block" type="submit">Go</button>
    </form>


2

<form id="banner-message">
    <input value=""
    name="email" 
    id="inputEmail"
    class="form-control"
    placeholder="email"
    required="" 
    autofocus=""  
    oninvalid="this.setCustomValidity('Not Valid')"                                               oninput="setCustomValidity('')"
    pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$">

    <button class="btn btn-lg  btn-block" type="submit">Go</button>
</form>


1

您还可以仅设置 title 属性:

<form id="banner-message">
    <input value=""
    placeholder="email"
    required="" 
    title="Not Valid"
    pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$">

    <button class="btn btn-lg  btn-block" type="submit">Go</button>
</form>


虽然在Chrome/Firefox中可以工作,但在Safari中无法工作。 - aalimovs

0
还要注意在输入标签中添加oninput="this.setCustomValidity('')"。因为如果不这样做,你可能会遇到警告信息混杂的情况。(一个输入标签的警告信息出现在另一个输入标签上)

-1
Hyyan Abo Fakher的答案有点可行,但是存在缺陷,因为我们使用setCustomValidity来设置“customError”有效状态,这会导致很多错误的正面验证。
我们应该使用onChange而不是oninvalid,并检查我们期望的错误的有效性状态并忽略customError。 这段代码适用于React:
<input
  ...
  onChange={event => {
    const target = event.target as HTMLInputElement;
    if (target?.validity?.patternMismatch) {
      target?.setCustomValidity(customInputError);
    } else {
      target?.setCustomValidity('');
    }}

在这里,我只设置了自定义错误消息,当我看到“patternMismatch”有效状态时。如果您想检查所有状态,请检查除target?.validity?.customError之外的所有状态,因为它是一个误报(由我们的setCustomValidity调用设置)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接