Validating HTML input with javascript

I want to check the html input that works on all platforms, i.e. Chrome, Internet Explorer, Mozilla, Firefox, Safari and Opera for PC, as well as iOS and Android.

I want to limit the input to numbers between a certain range, for example (from 1 to 59). Also I have another input element in the same form. I also want to check if there is input 1 <Enter 2, otherwise enter the error message. Please help.

I tried the following two options that do not work on all platforms:

<td align="center"><input id="SH1" name="sh1" type="number" min="1" max="59" align="center" /></td> <td align="center"><input id="SM1" name="sm1" type="text" maxlength="2" onkeypress='return event.charCode >= 48 && event.charCode <= 57' /></td> 
+5
source share
2 answers

For compatibility with almost every browser, use your own JavaScript. Below is a simple example of your requirement.

 <script language="javascript"> function validate() { var val1 = parseInt(document.getElementById('val1').value); var val2 = parseInt(document.getElementById('val2').value); minMaxRange(val1, val2); comparison(val1, val2); } function minMaxRange(value1, value2) { if (value1 < 1 || value2 < 1) { alert("Minimum value should be 1"); } if (value1 > 59 || value2 > 59) { alert("Maximum value should be 59"); } } function comparison(value1, value2) { if (value1 > value2) { alert("Value2 should be greater than Value1"); } } </script> <body> <p><span>Value 1 : </span> <input type="text" id="val1"> </p> <p><span>Value 2 : </span> <input type="text" id="val2"> </p> <p> <input type="button" value="Validate" onClick="validate()"> </p> </body> 
0
source

Well, let's say there are two inputs, as it should

 <input id="input1" type="number"> <input type="input2" type="number"> 

Now JS: (using jQuery)

 if($("#input1").val()<1 || $("#input1").val()>59) alert("Error"); if($("#input1").val() < $("#input2").val()) alert("Error"); 

Remember to include the jQuery library before this code.

Now, if you want to check it during input, follow these steps:

  $("[id^=input]").keyUp(function(){ if($("#input1").val()<1 || $("#input1").val()>59) alert("Error"); if($("#input1").val() < $("#input2").val()) alert("Error"); }) 
0
source

All Articles