2

I am trying to put custom validation on HTML5 input control time. I am able to successfully put the custom validation but it's also making it required even tough required is false for the control.

Here is my code:

<input type="time" value="8:00"
  oninvalid="this.setCustomValidity('Enter Valid Time')"
  oninput="setCustomValidity('')"/>

I also tried title attribute but didn't work. Input could be not required.

Update: Following code is working now:

<input type="time" value="8:00"
  oninvalid="this.setCustomValidity('Enter Valid Time')"
  oninput="this.setCustomValidity(''); return false;"/>

It shows me perfect validation if I put invalid value and click on Submit,but when I clear it and click on submit it is forcing me to have value in the textbox even tough it is not required.

Armaan Labib
  • 125
  • 1
  • 2
  • 16
  • Did you try having return false; at the end of your functions? Also why does one function call start with "this." and the other doesn't? – Anthony McGrath Dec 25 '17 at 08:21
  • Return false; on invalid? I copied the code from https://stackoverflow.com/questions/5272433/html5-form-required-attribute-set-custom-validation-message – Armaan Labib Dec 25 '17 at 08:26
  • @AnthonyMcGrath I tried `return false;` at the end of `oninput` function and it worked. Now, if I click on "x" button on `input` to clear the time then it works fine but if I go to time and remove time with backspace it still gives the validation. – Armaan Labib Dec 25 '17 at 08:31
  • @AnthonyMcGrath I updated my question please check. – Armaan Labib Dec 25 '17 at 08:56
  • It looks like having an empty value may constitute being invalid. From the accepted answer of the stackoverflow link you attached, this code: if (!e.target.validity.valid) { e.target.setCustomValidity("This field cannot be left blank"); } you may want to investigate this condition for empty strings – Anthony McGrath Dec 29 '17 at 07:07

0 Answers0