将 'Please match the format requested.' 更改为其他内容?

Change 'Please match the format requested.' to something else?

有没有简单的方法来自定义当 pattern: "([A-Za-z0-9\-\_]+)" 参数不满足并出现此消息时出现的消息:

例如

<%= f.text_field :username, pattern: "([A-Za-z0-9\-\_]+)" %>

您可以添加“标题”属性以附加到该消息:

<%= f.text_field :username, pattern: "([A-Za-z0-9\-\_]+)" , title: "Letters, numbers, hyphen, and underscore Only"%>

这将导致以下消息:

Please match the format requested: Letters, numbers, hyphen, and underscore Only

否则,对于更多自定义消息,您可以使用客户端验证(通过 javascript) server side validations (via rails and ActiveModel

对于完全自定义的消息,您必须使用 JavaScript。

const username = document.querySelector("#user_username");
username.addEventListener("invalid", ({ target }) => {
  target.setCustomValidity("Hello World!");
});
username.addEventListener("change", ({ target }) => {
  target.setCustomValidity("");
});
<form>
<input id="user_username" name="user[username]" pattern="[A-Za-z0-9_-]+" />
<input type="submit" />
</form>

您可以用类似的方式将其添加到 Rails 视图中:

<%= f.text_field :username, pattern: "[A-Za-z0-9_-]+" %>

...

<script>
const username = document.querySelector("#user_username");
username.addEventListener("invalid", ({ target }) => {
  target.setCustomValidity("Hello World!");
});
username.addEventListener("change", ({ target }) => {
  target.setCustomValidity("");
});
</script>

如果您更频繁地需要这种功能,或者想要一个更简洁的解决方案,您可能需要编写一些 unobtrusive JavaScript。例如:

function useCustomValidity({ target }) {
  target.setCustomValidity(target.getAttribute("custom-validity"));
}
function clearCustomValidity({ target }) {
  target.setCustomValidity("");
}

document.querySelectorAll("input[custom-validity]").forEach((input) => {
  input.addEventListener("invalid", useCustomValidity);
  input.addEventListener("change", clearCustomValidity);
});

加载上述 JavaScript(使用 Turbolinks 时需要添加额外的处理程序)。您现在可以看到以下视图:

<%= f.text_field :username, pattern: "[A-Za-z0-9_-]+", 'custom-validity': 'Hello World!' %>

另请参阅:MDN Input: Client-side validation