使用JavaScript验证表单 [英] Validate a form using JavaScript

查看:134
本文介绍了使用JavaScript验证表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  function validateForm(){
var x = document.forms [myForm] [fname] .value;
if(x == null || x ==){
alert(名字必须填写);
返回false;
}}
<! - html部分 - >
< form name =myFormaction =demo_form.asponsubmit =return validateForm()method =post>
名字:< input type =textname =fname>
< input type =submitvalue =提交>
< / form>< br>

这个代码的问题是按submit按钮触发 validateForm 函数。

解决方案

通过以下操作替换输入元素的代码:

 < input type =textonblur =return validateForm(); NAME = FNAME > 

我猜这就是你要找的东西


I am a beginner and I have written a code for validating the form as:

function validateForm(){
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
alert("First name must be filled out");
return false;
  }}
  <!-- html part-->
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form><br>

The problem with this code is pressing submit button triggers the validateForm function. How to call the function when the object losses focus?

解决方案

replace your input element's code by following

<input type="text" onblur="return validateForm();" name="fname">

i guess thats what you are looking for

这篇关于使用JavaScript验证表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆