Skip to content

Instantly share code, notes, and snippets.

@earlgreyxxx
Created November 1, 2020 09:40
Show Gist options
  • Save earlgreyxxx/adea98601eca215c7467c8491df0a59c to your computer and use it in GitHub Desktop.
Save earlgreyxxx/adea98601eca215c7467c8491df0a59c to your computer and use it in GitHub Desktop.
/******************************************************************
入力必須の際のエラーメッセージをカスタマイズします。
usage:
<input type="text" pattern="^[0-9]*$" name="hogehoge" />
$('input[type=text]').validity('半角数字で入力してください');
*******************************************************************/
;
(function($,undefined)
{
//デフォルト値
$.validityMessage = 'この項目は入力必須です。';
var validity = function(message)
{
if(message.length == 0)
message = $.validityMessage;
$(this)
.on('invalid',function(ev) {
if(this.validity.valueMissing || this.validity.patternMismatch || this.validity.typeMismatch)
{
this.setCustomValidity(message);
}
else
{
this.setCustomValidity('');
ev.preventDefault();
}
})
.on('input',function(ev) {
this.setCustomValidity('');
});
};
//plugin body
$.fn.validity = function(message)
{
return this.each(function()
{
validity.call(this,message);
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment