如何使用 JavaScript 为空输入字段添加表单验证?
要使用 JavaScript 为空输入字段添加表单验证,代码如下 −
示例
<!DOCTYPE html> <html> <head></head> <h1>JavaScript empty input field validation example</h1> <form name="Form1" onsubmit="return emptyValidation()" required> Name: <input type="text" name="firstName" /> <input type="submit" value="Submit" /> </form> <h2>Submit the form empty to see the validation performed</h2> <script> function emptyValidation() { var formField = document.forms["Form1"]["firstName"].value; if (formField == "" || x == null) { alert("Name must be filled out"); return false; } } </script> </body> </html>
输出
上面的代码将产生以下输出 −
当提交空表单 −
广告