I want to validate an html input which works on all platforms ie Chrome,Internet Explorer, Mozilla, Firefox, Safari & Opera for PC as well as iOS and Android.
I want to restrict the input to numbers between a particular range for eg (1 to 59). Also I have another input element in the same form. I also want to check if Input 1< Input 2, else give an error message. Please help.
I have tried the following two options which doesn't 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>
To compatible with almost every browser, use native JavaScript. An simple example for your requirement is follows.
<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>
Ok, let's say there are two inputs as follow
<input id="input1" type="number">
<input type="input2" type="number">
Now the JS:(Using jQuery)
if($("#input1").val()<1 || $("#input1").val()>59)
alert("Error");
if($("#input1").val() < $("#input2").val())
alert("Error");
Remember to include jQuery library before this code.
Now if you want to check it during input do following;
$("[id^=input]").keyUp(function(){
if($("#input1").val()<1 || $("#input1").val()>59)
alert("Error");
if($("#input1").val() < $("#input2").val())
alert("Error");
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.