Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...