Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

javascript - html5 oninvalid doesn't work after fixed the input field

I have this input code in my form:

<input maxlength="255" id="information_name" name="information[name]" oninvalid="check(this)" placeholder="Nombre Completo" required="required" size="30" style="width:528px;height:25px;" tabindex="3" type="text">

I change the oninvalid message with this javascritp code:

<script>
 function check(input) {
   if (input.value == "") {
     input.setCustomValidity('Debe completar este campo.');
   } else  {
     input.setCustomValidity('Debe corregir este campo.');
   }

 }
</script>

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???

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

<input required maxlength="255" id="information_name" minlength=1 name="information[name]" oninvalid="setCustomValidity('Should not be left empty.')" 
   oninput="setCustomValidity('')" />

There is no need to use Javascript for this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...