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

5.1k Views Asked by At

Is there an easy way to customise the message that appears when the pattern: "([A-Za-z0-9\-\_]+)" argument is not satisfied and this message appears:

> Please match the format requested

e.g.

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

There are 2 best solutions below

2
On BEST ANSWER

You can add a "title" attribute to append on to that message:

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

This will result in the following message:

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

Otherwise, for more custom messages, you can use client side validation (via javascript) server side validations (via rails and ActiveModel)

0
On

For a fully custom message you must use 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>

You could add this in your Rails view in a similar manner:

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

If you need this sort of functionality more often, or want a cleaner solution you might want to write some unobtrusive JavaScript. For example:

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);
});

With the above JavaScript being loaded (you need to add additional handlers when using Turbolinks). You can now have the following view:

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

See also: MDN Input: Client-side validation