使用JavaScript进行表单验证?

时间:2015-04-18 11:17:08

标签: javascript forms validation

我尝试使用JavaScript进行表单验证,但是我似乎没有得到任何回复,即使是在那里也没有提醒。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

    <head>
        <title>Example Form</title>
        <script type="text/javascript">
            function CheckForBlank() {

                if(document.getElementById('name').value="") {
                    alert("enter something valid");
                    return false;
                }
            }
        </script>
    </head>
    <body>

        <form method="post" action="2013.php" onsubmit="return CheckForBlank();">
            Name: <input type="text" name="name" id="name"/>
            Age: <input type="text" name="age" id="age"/>
            Email: <input type="text" name="email" id="email"/>
            <p><input type="submit" value="Submit" /></p>
        </form>
    </body>
</html>

6 个答案:

答案 0 :(得分:4)

在javascript中使用===或==进行条件检查。

if(document.getElementById('name').value === ""){
   alert("enter something valid");
   return false;
}

答案 1 :(得分:2)

你必须使用==进行比较。=用于分配

if(document.getElementById('name').value == ""){
       alert("enter something valid");
       return false;
    }

答案 2 :(得分:1)

Working Demo

此处您的问题仅针对if条件!您必须在JavaScript中使用=====进行比较。

以下是更正的脚本!

function CheckForBlank() {
        if(document.getElementById('name').value=="") {
            alert("enter something valid");
            return false;
        }
    }

如果您删除或避免return false,表单回发即使验证失败!所以,return false意味着,在if之后退出函数是必须的,并且在另一个答案中错过了!!

答案 3 :(得分:1)

您正在使用=作为赋值运算符,使用==比较运算符可以正常工作

<head>
    <title>Example Form</title>
    <script type="text/javascript">
        function CheckForBlank() {

            if(document.getElementById('name').value=="") {
                alert("enter something valid");
                return false;
            }
        }
    </script>
</head>
<body>

    <form method="post" onsubmit="return CheckForBlank();">
        Name: <input type="text" name="name" id="name"/>
        Age: <input type="text" name="age" id="age"/>
        Email: <input type="text" name="email" id="email"/>
        <p><input type="submit" value="Submit" /></p>
    </form>
</body>

答案 4 :(得分:0)

尽管您将Javascript附加到表单提交事件,而不是按钮提交事件,但我不敢相信直到现在还没有意识到这一点。正常的浏览器验证有效(即输入[type =“ email],required =” required“等)。

在Firefox和Chrome中工作。

// jQuery example attaching to a form with the ID form
$(document).on("submit", "#form", function(e) {
    e.preventDefault();
    console.log ("Submitted! Now serialise your form and AJAX submit here...");
})

答案 5 :(得分:-1)

我已经使用bootstrap做了更好的表单验证方法。您可以查看我的代码集http://codepen.io/abhilashn/pen/bgpGRw

&#13;
&#13;
var g_UnFocusElementStyle = "";
var g_FocusBackColor = "#FFC";
var g_reEmail = /^[\w\.=-]+\@[\w\.-]+.[a-z]{2,4}$/;
var g_reCell = /^\d{10}$/;
var g_invalidFields = 0;

function initFormElements(sValidElems) {
	var inputElems = document.getElementsByTagName('textarea');
	for(var i = 0; i < inputElems.length; i++) {
		com_abhi.EVENTS.addEventHandler(inputElems[i], 'focus', highlightFormElement, false);
		com_abhi.EVENTS.addEventHandler(inputElems[i], 'blur', unHightlightFormElement, false);
	}
	/* Add the code for the input elements */
	inputElems = document.getElementsByTagName('input');
	for(var i = 0; i < inputElems.length; i++) {
		if(sValidElems.indexOf(inputElems[i].getAttribute('type') != -1)) {
			com_abhi.EVENTS.addEventHandler(inputElems[i], 'focus', highlightFormElement, false);
			com_abhi.EVENTS.addEventHandler(inputElems[i], 'blur', unHightlightFormElement, false);
		}
	}
	
	/* submit handler */
	
	
	com_abhi.EVENTS.addEventHandler(document.getElementById('form1'), 'submit' , validateAllfields, false);
	
	/* Add the default focus handler */
	document.getElementsByTagName('input')[0].focus();
	
	/* Add the event handlers for validation */
	com_abhi.EVENTS.addEventHandler(document.forms[0].firstName, 'blur', validateFirstName, false);
	com_abhi.EVENTS.addEventHandler(document.forms[0].email, 'blur', validateEmailAddress, false);
	com_abhi.EVENTS.addEventHandler(document.forms[0].address, 'blur', validateAddress, false);
	com_abhi.EVENTS.addEventHandler(document.forms[0].cellPhone, 'blur', validateCellPhone, false);
}

function highlightFormElement(evt) {
	var elem = com_abhi.EVENTS.getEventTarget(evt);
	if(elem != null) {
		elem.style.backgroundColor = g_FocusBackColor;
	}
}

function unHightlightFormElement(evt) {
	var elem = com_abhi.EVENTS.getEventTarget(evt);
	if(elem != null) {
		elem.style.backgroundColor = "";
	}
}

function validateAddress() {
	var formField = document.getElementById('address');
	var ok = (formField.value != null && formField.value.length != 0);
	var grpEle = document.getElementById('grpAddress');
	if(grpEle != null) {
		if(ok) {
			grpEle.className = "form-group has-success has-feedback";
			document.getElementById('addressIcon').className = "glyphicon glyphicon-ok form-control-feedback";
			document.getElementById('addressErrorMsg').innerHTML = "";
		}
		else  {
			grpEle.className = "form-group has-error has-feedback";
			document.getElementById('addressIcon').className = "glyphicon glyphicon-remove form-control-feedback";
			document.getElementById('addressErrorMsg').innerHTML = "Please enter your address";
		}
		return ok;
	}
	
}

function validateFirstName() {
	var formField = document.getElementById('firstName');
	var ok = (formField.value != null && formField.value.length != 0);
	var grpEle = document.getElementById('grpfirstName');
	if(grpEle != null) {
		if(ok) {
			grpEle.className = "form-group has-success has-feedback";
			document.getElementById('firstNameIcon').className = "glyphicon glyphicon-ok form-control-feedback";
			document.getElementById('firstNameErrorMsg').innerHTML = "";
		}
		else  {
			grpEle.className = "form-group has-error has-feedback";
			document.getElementById('firstNameIcon').className = "glyphicon glyphicon-remove form-control-feedback";
			document.getElementById('firstNameErrorMsg').innerHTML = "Please enter your first name";
		}
		return ok;
	}
}

function validateEmailAddress() {
	var formField = document.getElementById('email');
	var ok = (formField.value.length != 0 && g_reEmail.test(formField.value));
	var grpEle = document.getElementById('grpEmail');
	if(grpEle != null) {
		if(ok) {
			grpEle.className = "form-group has-success has-feedback";
			document.getElementById('EmailIcon').className = "glyphicon glyphicon-ok form-control-feedback";
			document.getElementById('emailErrorMsg').innerHTML = "";
		}
		else {
			grpEle.className = "form-group has-error has-feedback";
			document.getElementById('EmailIcon').className = "glyphicon glyphicon-remove form-control-feedback";
			document.getElementById('emailErrorMsg').innerHTML = "Please enter your valid email id";
		}
	}
	return ok;
}

function validateCellPhone() {
	var formField = document.getElementById('cellPhone');
	var ok = (formField.value.length != 0 && g_reCell.test(formField.value));
	var grpEle = document.getElementById('grpCellPhone');
	if(grpEle != null) {
		if(ok) {
			grpEle.className = "form-group has-success has-feedback";
			document.getElementById('cellPhoneIcon').className = "glyphicon glyphicon-ok form-control-feedback";
			document.getElementById('cellPhoneErrorMsg').innerHTML = "";
		}
		else {
			grpEle.className = "form-group has-error has-feedback";
			document.getElementById('cellPhoneIcon').className = "glyphicon glyphicon-remove form-control-feedback";
			document.getElementById('cellPhoneErrorMsg').innerHTML = "Please enter your valid mobile number";
		}
	}
	return ok;
}



function validateAllfields(e) {
	/* Need to do it this way to make sure all the functions execute */
	
	var bOK = validateFirstName();
	bOK &= validateEmailAddress();
	bOK &= validateCellPhone(); 
	bOK &= validateAddress(); 
	

	if(!bOK) {
		alert("The fields that are marked bold and red are required. Please supply valid\n values for these fields before sending.");
		com_abhi.EVENTS.preventDefault(e);
	}
	
	
}

com_abhi.EVENTS.addEventHandler(window, "load", function() { initFormElements("text"); }, false);
&#13;
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
			<div class="row">
				<h1 class="text-center">Interactive form validation using bootstrap</h1>
				<form id="form1" action="" method="post" name="form1" class="form-horizontal" role="form" style="margin:10px 0 10px 0">
					<div id="grpfirstName" class="form-group">
						<label for="firstName" class="col-sm-2 control-label"><span class="text-danger">* </span>First Name</label>
						<div class="col-sm-10">
						  <input type="text" class="form-control" id="firstName" placeholder="Enter first name">
						   <span id="firstNameIcon"  class=""></span>
						   <div id="firstNameErrorMsg" class="text-danger"></div>
						</div>
					</div>
					
					<div class="form-group">
						<label for="lastName" class="col-sm-2 control-label">Last Name</label>
						<div class="col-sm-10">
						  <input type="text" class="form-control" id="lastName" placeholder="Enter last name">
						</div>
					</div>
					
					<div id="grpEmail" class="form-group">
						<label for="lastName" class="col-sm-2 control-label"><span class="text-danger">* </span>Email </label>
						<div class="col-sm-10">
						  <input type="email" class="form-control" id="email" placeholder="Enter email">
						   <span id="EmailIcon"  class=""></span>
						     <div id="emailErrorMsg" class="text-danger"></div>
						</div>
					</div>
					
					<div id="grpCellPhone" class="form-group">
						<label for="lastName" class="col-sm-2 control-label"><span class="text-danger">* </span>Cell Phone </label>
						<div class="col-sm-10">
						  <input type="text" class="form-control" id="cellPhone" placeholder="Enter Mobile number">
						   <span id="cellPhoneIcon"  class=""></span>
						     <div id="cellPhoneErrorMsg" class="text-danger"></div>
						</div>
					</div>
					
					<div class="form-group" id="grpAddress">
						<label for="address" class="col-sm-2 control-label"><span class="text-danger">* </span>Address </label>
						<div class="col-sm-10">
							<textarea id="address" class="form-control"></textarea>
							 <span id="addressIcon"  class=""></span>
							 <div id="addressErrorMsg" class="text-danger"></div>
						</div>
					</div>
					<div class="form-group">
						<div class="col-sm-offset-2 col-sm-10">
						  <button type="submit" class="btn btn-success">Save</button>
						</div>
					</div>
			
		</form>
			</div> <!-- End of row -->
		</div> <!-- End of container -->
&#13;
&#13;
&#13;

请检查我的codepen以更好地理解代码。