Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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\-\_]+)" %>
like image 884
stevec Avatar asked Oct 28 '25 10:10

stevec


2 Answers

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)

like image 163
engineersmnky Avatar answered Oct 29 '25 23:10

engineersmnky


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

like image 30
3limin4t0r Avatar answered Oct 30 '25 01:10

3limin4t0r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!