i have this code which validates fields using regex expressions. at this moment it makes a popup in case something is wrong. i'd like to let go of this and to show a message maybe next to the field or above it. any help please?
here is the code:
<script>
function validate(form) {
var pwd = form.elements.pasa.value;
var eml = form.elements.pasa2.value;
if(5 > pwd.length || pwd.length > 25){
alert("error");
return false;
}
var rgx = /[a-zA-Z]|\d+/;
if(!rgx.test(pwd)){
alert("error");
return false;
}
rgx = /\s/;
if(rgx.test(pwd)){
alert("error");
return false;
}
if(8 > eml.length || eml.length > 40){
alert("error");
return false;
}
var rgx = /^\s*[a-z\d_]+(\.[a-z\d_]+)*#[a-z\d\-]{1,255}\.[a-z]{2,6}\s*$/;
if(!rgx.test(eml)){
alert("error");
return false;
}
rgx = /\s/;
if(rgx.test(eml)){
alert("error");
return false;
}
return true;
}
</script>
and the form:
<form name="Form1" method="post" action="action1.php" language="javascript" onSubmit="return validate(this);" id="Form1">
<input name="pasa" class="field" type="text">
<input name="pasa2" class="field" type="text">
<input type="submit">
</form>
thanks
Replace alert() calls with code that puts a message in the right place. Things like createElement, appendChild and other fundamental DOM methods might be useful.
Related
I am doing some form validation in JSP, on click on submit button "validate_access()" function is not called or not working. Sometimes this function displays a alret box and then stop doing any thing . Please tell what is wrong with this piece of code.Here is a piece of code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Data management system</title>
<script language="JavaScript" type="text/javascript">
function validate_access()
{
var a = document.forms["myForm1"]["MISDN"].value;
var b = document.forms["myForm1"]["Issue"].value;
var c = document.forms["myForm1"]["SR"].value;
var d = document.forms["myForm1"]["date"].value;
var numbers = /^[0-9]+$/;
var alpha= /^[a-zA-Z]+$/;
var Datee= /^\d{1, 2}\/\d{1, 2}\/\d{4}$/;
if(document.myform1.MISDN.value=="" && document.myform1.Issue.value=="" && document.myform1.SR.value=="" && document.myform1.date.value=="")
{
alert("Manadotry fields should not left blank");
document.myform1.MISDN.focus();
document.myform1.Issue.focus();
document.myform1.SR.focus();
document.myform1.date.focus();
return false;
}
else if(!a.value.match(numbers))
{
alert('Please input numeric characters only');
document.myform1.MISDN.focus();
return false;
}
else if(!(b.value.match(numbers) && b.value.match(alpha)))
{
alert('Please input numeric and alphabets only');
document.myform1.Issue.focus();
return false;
}
else if(!c.value.match(numbers))
{
alert('Please input numeric characters only');
document.myform1.SR.focus();
return false;
}
else if(!d.value.match(Datee))
{
alert('Please input correct date');
document.myform1.date.focus();
return false;
}
else
return true;
}
</script>
</head>
<body>
<div class="main">
<div class="header"></div>
<div class="continer">
<div class="myform1" style="height:200px; width:300px; float:left;">
<h2>1344 Access</h2>
<form name="myform1" action="access.jsp" method="get" onsubmit="return validate_access()">
<br/>MSISDN:<input type="text" name="MISDN" maxlength="11">
<br/>Issue:<input type="text" name="Issue" maxlength="13">
<br/>SR:<input type="text" name="SR">
<br/>Date:<input type="text" name="date" value="dd/mm/yy">
<br/><input type="submit" value="Submit">
<br/><input type="reset" name="Reset">
</form>
</div>
<div class="myform2" style="float:left;height:200px; width:300px;">
<h2>O.C.S</h2>
<form name="myform2" action="ocs.jsp" method="post" onsubmit="return validate_ocs()">
<br/>MSISDN:<input type="text" name="MISDN" maxlength="11">
<br/>SR:<input type="text" name="SR">
<br/>REASON:<input type="text" name="reason">
<br/><input type="submit" value="Submit">
<br/><input type="reset" name="Reset">
</form>
</div>
</div>
</div>
</body>
Problems in your javascript are:
the first if condition check is wrong you mean || in place of &&.
then next when you call match method on empty string a error probably raise like:
Uncaught TypeError: Cannot read property 'match' of undefined
you calling .focus() continuously that doesn't making any sense, call once with a condition check.
There is something wrong in this line:var a = document.forms["myForm1"]["MISDN"].value;
Look at your source code, your form name is "myform1" not "myForm1".
JavaScript is case sensitive.
http://en.wikipedia.org/wiki/JavaScript_syntax
in your js:
document.forms["myForm1"]
but in your form(html) it is:
<form name="myform1"
Try this:
function validate_access()
{
var a = document.forms["myForm1"]["MISDN"].value;
var b = document.forms["myForm1"]["Issue"].value;
var c = document.forms["myForm1"]["SR"].value;
var d = document.forms["myForm1"]["date"].value;
var numbers = /^[0-9]+$/;
var alpha= /^[a-zA-Z]+$/;
var Datee= /^\d{1, 2}\/\d{1, 2}\/\d{4}$/;
if(a == "" && b == "" && c == "" && d == "")
{ //as you have default value for d (date field), this condition will never match;
//either you can remove default value or provide different logic
alert("Manadotry fields should not left blank");
document.myForm1.MISDN.focus();
document.myForm1.Issue.focus();
document.myForm1.SR.focus();
document.myForm1.date.focus();
return false;
}
else if(a == "" && !a.match(numbers))
{
alert('Please input numeric characters only');
document.myForm1.MISDN.focus();
return false;
}
else if(!(b.match(numbers) && b.match(alpha)))
{
alert('Please input numeric and alphabets only');
document.myForm1.Issue.focus();
return false;
}
else if(!c.match(numbers))
{
alert('Please input numeric characters only');
document.myForm1.SR.focus();
return false;
}
else if(!d.match(Datee))
{
alert('Please input correct date');
document.myForm1.date.focus();
return false;
}
else
return true;
}
Your mistakes:
(i) form name spelling mistake (caseSensitive)
(ii) you used HTMLElement.value.value to check (in if conditions)
For example:
var a = document.forms["myForm1"]["MISDN"].value;
a.value.match(numbers); // it simply means HTMLElement.value.value (which will never work)
I'm trying to submit a HTML form, only when all the fields do not return false in the Javascript code.
My HTML looks like this, for simplicity I have just kept the name and email
<form method="post" action="RegistrationServlet" class="iform"
onsubmit="return sendForm();">
<ul><li><label for="YourName">*Your Name <span id="regNameErr"></span></label>
<input class="itext" type="text" name="YourName" id="YourName" /></li>
<li><br /><label for="YourEmail">*Your Email <span id="regEmailErr"></span></label>
<input class="itext" type="text" name="YourEmail" id="YourEmail" /></li>
<li><input type="submit" value="Submit" class="ibutton" name="SendaMessage"
id="SendaMessage" value="Send a Message!" readonly="readonly" /></li></ul></form>
The Javascript looks like this, again for simplicity I am just checking 2 fields:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
window.sendForm = function() {
if (($("#YourName").val() == "") || ($("#YourName").val().length > 55)) {
$("#YourName").addClass("required");
window.scroll(0, 190);
$("#regNameErr").text("required");
return false;
}
if ($("#YourEmail").val() == "") {
$("#YourEmail").addClass("required");
window.scroll(0, 190);
$("#regEmailErr").text("required");
return false;
}
if (!isEmailValid($("#YourEmail").val())) {
$("#YourEmail").addClass("required");
window.scroll(0, 190);
$("#regEmailErr").text("required");
return false;
}
$("#SendaMessage").val("Please Wait...");
return true;
}
Why is the sendForm() function not repeatedly being called to check that all fields are correct before submitting. Any ideas?
Also I understand that I can add a bounty after 2 days but I am not seeing any button on the editor.
Can you help?
sendForm is called only once per submit - this how it works, and there is no reason to call it multiple times.
If you want to have all your fields checked on submit - you should not return after each check. Instead you should postpone this action until the all fields are verified, and introduce some flag to remember results:
function() {
var formValid = true;
if (($("#YourName").val() == "") || ($("#YourName").val().length > 55)) {
...
formValid = false;
}
if ($("#YourEmail").val() == "") {
...
formValid = false;
}
if (!isEmailValid($("#YourEmail").val())) {
...
formValid = false;
}
if (!formValid) {
return false;
}
$("#SendaMessage").val("Please Wait...");
return true;
}
Side note. Have you considered any jQuery validation plugins for this? Might save you some implementation and maintenance efforts.
I've read many posts considering this problem and for some reason none of the solutions work for me. I have several js functions for validation that are called in the main one that is appointed to the onSubmit tag in the form. Here is the js code:
<script type="text/javascript">
function validacijaForme() {
var username = document.getElementById('usname');
var email = document.getElementById('email');
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
if(validacijaUsername(username) && validacijaEmail(email) && validacijaSifri(pass1,pass2))
{
alert('success');
return true;
}
return false;
}
</script>
<script type="text/javascript">
function validacijaSifri(fieldId1, fieldId2)
{
var two = document.getElementById(fieldId1).value;
var three = document.getElementById(fieldId2).value;
if(two == three) { return true; }
alert("Warning!! passcodes must match!!!");
return false;
}
</script>
<script type="text/javascript">
function validacijaUsername(usname)
{
var letters = /^[A-Za-z]+$/;
if(letters.test(usname.value))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
document.getElementById('usrname').focus();
return false;
}
}
</script>
<script type="text/javascript">
function validacijaEmail(email)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(mailformat.test(email))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
document.getElementById(email).focus();
return false;
}
}
and here is the html form code
<form class="form-signin" onSubmit="return validacijaForme();" name="registerForm" method = "POST" action="test.php" enctype="multipart/form-data">
<h2 class="form-signin-heading">Registracija</h2>
<input type="text" class="form-control" placeholder="Username" name="usrname" id="usname" autofocus>
<input type="text" class="form-control" placeholder="E-mail" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="pass" id="pass1">
<input type="password" class="form-control" placeholder="Confirm password" id="pass2">
<button class="btn btn-lg btn-primary btn-block" name="dugme" type="submit">Register</button>
The problem is that all the alerts are working, meaning that those functions do validate the fields, and should return false, but the onSubmit tag doesn't seem to accept that value from the function.
The form doesn't submit and doesn't pass to test.php only if I type this:
<form class="form-signin" onSubmit="return false" name="registerForm" method = "POST" action="test.php" enctype="multipart/form-data">
submit the form with javascript submit()
<form id="myform" class="form-signin" onSubmit="validacijaForme();" name="registerForm"
method = "POST" action="test.php" enctype="multipart/form-data">
And in your function:
function validacijaForme() {
var username = document.getElementById('usname');
var email = document.getElementById('email');
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
if(validacijaUsername(username) && validacijaEmail(email) && validacijaSifri(pass1,pass2))
{
alert('success');
document.getElementById("myform").submit();
return false;
}
return false;
}
Your problem is related to your username id/name consistency. Use the console (F12) to debug this kind of thing.
<input type="text" class="form-control" placeholder="Username" name="usRname" id="usname" autofocus>
Change:
document.getElementById('usrname').focus();
To:
document.getElementById('usname').focus();
There are lots of errors in your code buddy | WORKING DEMO
function validacijaForme() {
var username = document.getElementById('usname');
var email = document.getElementById('email');
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
if(validacijaUsername(username) && validacijaEmail(email) && validacijaSifri(pass1,pass2))
{
alert('success');
return true;
}
return false;
}
function validacijaSifri(fieldId1, fieldId2)
{
var two = fieldId1.value;
var three = fieldId2.value;
if(two == three) { return true; }
alert("Warning!! passcodes must match!!!");
return false;
}
function validacijaUsername(usname)
{
var letters = /^[A-Za-z]+$/;
if(letters.test(usname.value))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
document.getElementById('usname').focus();
return false;
}
}
function validacijaEmail(email)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(mailformat.test(email.value))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
document.getElementById('email').focus();
return false;
}
}
How would I fix,"Expected End Of Statement" in the code below?
<script type="text/javascript">
function substitute() {
var myValue = document.getElementById('myTextBox').value;
if (myValue.length === 0) {
alert('Please enter a real value in the text box!');
return;
}
var myTitle = document.getElementById('title');
myTitle.innerHTML = myValue;
}
</script>
It keeps telling me line 57 which is this line:
<input type="submit" value="Click Me" onClick="substitute();">
Here is the complete HTA link:
http://pastebin.com/fMg5e4RN
Use <form onsubmit="return substitute()" and return true or false depending on validation. Remove type="javascript" or fix it as text/javascript
<script type="text/javascript">
function substitute() {
var myValue = document.getElementById('myTextBox').value;
if (myValue.length === 0) {
alert('Please enter a real value in the text box!');
return false;
}
// not sure what the following two lines are for
var myTitle = document.getElementById('title');
myTitle.innerHTML = myValue;
return true; // allow submit
}
</script>
and use
<form action="some action" onsubmit="return substitute();">
<input type="text" id="myTextBox"/>
<input type="submit" value="Click Me" />
</form>
I wrote a java script code in a JSP page,But when i try to submit the Page, my javascript validation code is not getting fired,Could any one help me what went wrong?
Here My Code:
<html>
<center><h3>Employee Absent Report</h3></center>
<head>
<script language="javascript" type="text/javascript">
function onFormSubmit(){
var countErrors = 0;
var strDt=document.getElementById("startdate").value;
var endDt=document.getElementById("todate").value;
var flag=false;
var eFlag = false;
if (IsEmpty(strDt)==false && IsEmpty(endDt)==true ) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (IsEmpty(strDt)==true && IsEmpty(endDt)==false ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
return true;
}
</script>
</head>
<body>
<form name="form" action="FormServlet" method="get" onsubmit="return onFormSubmit(); ">
<center>
<div id="formErrors" class="error"></div>
FromDate:
<input type="text" name="startdate" id="startdate"/>
<div id="divStartDate"></div>
<br>
ToDate:
<input type="text" name="todate" id="todate"/>
<div id="divExpiryDate"> </div>
<br>
<input type="submit" value="submit"/>
</center>
</form>
</body>
</html>
is there a method "IsEmpty" in javascript? I think that's the problem. If you have that defined in some other place, try running your code in Firefox and watch Error Console for errors.
Looks like a logical error to me. Try replacing this:
if (IsEmpty(strDt)==false && IsEmpty(endDt)==true ) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (IsEmpty(strDt)==true && IsEmpty(endDt)==false ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
with:
if (endDt.length==0) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (strDt.length==0) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
Do the validation this way
if (endDt === "") {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
return false;
}
if (strDt === "" ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
return false;
}
Hope this helps!
this is the working modified code
<script>
function onFormSubmit(event){
var countErrors = 0;
event.preventDefault();
var strDt=document.getElementById("startdate").value;
var endDt=document.getElementById("todate").value;
var flag=false;
var eFlag = false;
if ( IsEmpty(endDt)==true ) {
document.getElementById("divExpiryDate").innerHTML = "* Please Enter Expiry Date";
eFlag = true ;
}
if (IsEmpty(strDt)==true ) {
document.getElementById("divStartDate").innerHTML = "* Please Enter Start Date";
eFlag = true;
}
if(eFlag)
{
return false;
}
return true;
}
function IsEmpty(input)
{
if(input.replace(/^\s+|\s+$/g,"") === "") {
return true;
}
return false;
}