html5 oninvalid doesn't work after fixed the input field

匿名 (未验证) 提交于 2019-12-03 01:54:01

问题:

I have this input code in my form:

I change the oninvalid message with this javascritp code:

Here is the problem, if I clicked on submit and the field is empty, the field shome the error so I need to fill the field, but after fill the field, I still getting the warning even the fill is not empty.

What I'm doing wrong???

回答1:

You can set a custom validity message with setCustomValidity, however any non-blank string will cause the field to act as if it had an invalid value. You need to setCustomValidity('') to clear the invalidated state of the field.

If your validity is simple and controlled via field attributes, you can use object.willValidate to do the test and set the custom validity message:

oninvalid="this.setCustomValidity(this.willValidate?'':'your custom message')"



回答2:

If you set a value with setCustomValidity() then the field is invalid. That is setting a non-zero length string causes the browser to consider the field invalid. In order to take effects of your new input you have to clear the custom validity. Simply you can use the following:

There is no need to use Javascript for this.



回答3:

If you setCustomValidity to any value that is not the empty string then that will cause the input to be in the invalid state. So your condition is checking for a value, then setting the field to be invalid either way. Only setCustomValidity when the value in the field is actually invalid, otherwise set it to an empty string:



回答4:

For me only oninvalid="this.setCustomValidity(this.willValidate ? '' :'You must choose the account type from the list')" works. There are lots of issues while using it with IE.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!