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:
e.g.
<%= f.text_field :username, pattern: "([A-Za-z0-9\-\_]+)" %>
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:
e.g.
<%= f.text_field :username, pattern: "([A-Za-z0-9\-\_]+)" %>
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
You can add a "title" attribute to append on to that message:
This will result in the following message:
Otherwise, for more custom messages, you can use client side validation (via javascript) server side validations (via rails and ActiveModel)