I need a way to validate a form in new and old browsers.
This is my code:
<form name="myForm">
<input type="text" name="contactname" placeholder="Name" required>
<input type="email" name="contactemail" placeholder="Email" required>
<input type="number" name="contactphone" placeholder="Phone Number" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
<button type="submit">SEND</button>
</form>
This code works well in browsers that support HTML5, but it doesn't work in old browsers like internet explorer 8. So I tried to add onclick="validateform()"
in the submit button:
function validateform() {
// Support for old browsers
var x = document.forms["myForm"]["contactname"].value;
// if z is filled
var y = document.forms["myForm"]["contactemail"].value;
// if y is an email and it is filled
var z = document.forms["myForm"]["contactphone"].value;
// if z is a number
}
But then in the new browser it validates 2 times and it's annoying. So what is the correct way to implement validation that supports old browsers?
Check if browser supports HTML5 form validation or not then validate :
typeof document.forms["myForm"]["contactname"].checkValidity == 'function'
IF true then no need to validate(browser supports validation) else validate.
如果浏览器不支持HTML5表单验证,则从jQuery进行验证,请参见该演示-Jquery验证演示
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.