Ad

Pattern Attribute Only Passes After Page Reset

- 1 answer

I have added a pattern attribute to my custom input field in the Shopify add to cart form.

The problem is that the pattern validator won't pass unless i refresh the page after it has caught something in the validation.

I have tried to reset the form with .reset and it works, but the custom validation messages won't work in that case.

<input required class="required" id="add-your-name-here" type="text" pattern="^[A-Za-z_]{1,15}" placeholder="{{ section.settings.text-custom-name-placeholder }}" name="properties[Ditt namn]">
var input = document.getElementById('add-your-name-here');

input.oninvalid = function(event) {
  if ($(".wgcurrent").hasClass("en")) { 
    event.target.setCustomValidity("Letters only please");  
  } else if ($(".wgcurrent").hasClass("sv")) {
    event.target.setCustomValidity("Vänligen ange endast bokstäver");
  }  

}

It works like this, except that the custom validation message won't display.

var input = document.getElementById('add-your-name-here');

input.oninvalid = function(event) {
  if ($(".wgcurrent").hasClass("en")) { 
    document.getElementById("addtocart").reset();
    event.target.setCustomValidity("Letters only please");  
  } else if ($(".wgcurrent").hasClass("sv")) {
    document.getElementById("addtocart").reset();
    event.target.setCustomValidity("Vänligen ange endast bokstäver");
  }  

}

I want the validation to work without having to refresh the page as it's not a very nice user experience.

Ad

Answer

You need to clear the Custom Validation message on input event. To do so use,

setCustomValidity('');

Check working code snippet below.

var input = document.getElementById('add-your-name-here');

input.oninput = function(event){
	event.target.setCustomValidity('');
}

input.oninvalid = function(event) {
    event.target.setCustomValidity("Letters only please");  
}
<form action="#">
<input required class="required" id="add-your-name-here" type="text" pattern="^[A-Za-z_]{1,15}" placeholder="Add text here" name="properties[Ditt namn]">

<button type="submit">Submit</button>

</form>

More details on Constraints Validation at MDN

Ad
source: stackoverflow.com
Ad