The following code gives a simple sign up form and uses JavaScript to validate the user's input. When run in chrome, there are alerts as expected. But in IE and Firefox, the page only goes to adduser.php without alerts even nothing has been entered into the form.
CSS
.signup {
font: normal 14px helvetica;
color: #000000;
border: solid 6px #555555;
}
JS
function validate() {
var fail = "";
fail += validateForename(document.getElementById("forename").value);
fail += validateSurname(document.getElementById("surname").value);
fail += validateUsername(document.getElementById("username").value);
fail += validatePassword(document.getElementById("password").value);
fail += validateAge(document.getElementById("age").value);
fail += validateEmail(document.getElementById("email").value);
if (fail == "") return true;
else alert(fail);
return false;
}
function validateForename(str) {
if (str == "") return "No forename has been found\n";
return "";
}
function validateSurname(str) {
if (str == "") return "No surname has benn found\n";
return "";
}
function validateUsername(str) {
if (str == "") return "No username has been found\n";
if (str.length < 5) return "Username must be at least 5 characters\n";
if (/[^a-zA-Z0-9_-]/.test(str)) return "Only a-z, A-Z, 0-9, - and _ are allowed in username\n";
return "";
}
function validatePassword(str) {
if (str == "") return "Password can not be empty\n";
if (str.length < 6) return "Password must be at least 6 characters\n";
if (!/[0-9]/.test(str) || !/[a-z]/.test(str) || !/[A-Z]/.test(str)) return "Password must have at least one each of a-z, A-Z, 0-9\n";
return "";
}
function validateAge(str) {
if (isNaN(str)) return "No age has been found\n";
if (str < 18 || str > 110) return "Age must be between 18 and 110\n";
return "";
}
function validateEmail(str) {
if (str == "") return "No email address has been found\n";
if (!(str.indexOf('.') > 0 && str.indexOf('#') > 0) || /[^a-zA-Z0-9_-.#]/.test(str)) return "The email address is invalid\n";
return "";
}
HTML
<table class="signup" border="0" cellpadding="4" bgcolor="#eeeeee">
<th colspan="2" align="center">Sign Up</th>
<form method="post" action="adduser.php" onSubmit="return validate()">
<tr>
<td>Forname:</td>
<td>
<input type="text" name="forename" id="forename" maxlength="32" />
</td>
</tr>
<tr>
<td>Surname:</td>
<td>
<input type="text" name="surname" id="surname" maxlength="32" />
</td>
</tr>
<tr>
<td>Username:</td>
<td>
<input type="text" name="username" id="username" maxlength="16" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" id="password" maxlength="12" />
</td>
</tr>
<tr>
<td>Age:</td>
<td>
<input type="text" name="age" id="age" maxlength="3" />
</td>
</tr>
<tr>
<td>Email:</td>
<td>
<input type="text" name="email" id="email" maxlength="64" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Signup" />
</td>
</tr>
</form>
</table>
The problem is on this line (55):
if (!(str.indexOf('.') > 0 && str.indexOf('#') > 0) || /[^a-zA-Z0-9_-.#]/.test(str)) return "The email address is invalid\n";
The character class you declared is invalid:
/[^a-zA-Z0-9_-.#]/ //--> Wrong
/[^a-zA-Z0-9_.#-]/ //--> Right
The browser tries to interpret _-. as a range of characters between _ and ., and sorely fails.
The following regex (line 55) produces an error in Firebug (SyntaxError: invalid range in character class) :
/[^a-zA-Z0-9_-.#]/
Try this one instead :
/[^\w-]+/gi
Works for me now in FF and IE 11.
This regular expression object is not very reliable:
/[^a-zA-Z0-9_-.#]/
Chrome tolerates that, but Firefox doesn't understand that _-. is not a character range, like a-z. You can move - to the very end to avoid ambiguity. Final regexp becomes (i means case insensitive match)
/[^a-z0-9_.#-]/i
Related
<form name="frmfeed" method="post" action="demo/admin/formprocess.php" onSubmit="return validate_form()">
<table>
<tbody>
<tr>
<td>Name Of Applicant</td>
<td><input type="text" name="name" id="name" placeholder="Full Name" onFocus="this.value = '';" onBlur="if (this.value == '') {this.value = '';}" class="input_style"></td>
</tr>
<tr>
<td>Mobile Number: (10 Digit)*</td>
<td><input id="number" type="text" placeholder="Mobile Number" class="input_style" onblur=" if(checkPhone(this.value)==false){this.value=''}"/></td>
</tr>
</form>
This is javascript code that I have used:
function checkPhone(input) {
var phoneno = /^\d{10}$/;
if(input.value.match(phoneno);
{return false;}
return true;
}
I am trying to validate the phone number entered by the user but match function is not working. I cant find the error. Any help would be appreciated. thanks.
Check with following function
function checkPhone(input) {
var pattern = new RegExp(/^[0-9]{10,10}$/);
if(pattern.test(input)) { return true; }
return false;
}
If returns true then match is correct else test pattern is wrong.
I am struggling to understand where there is a mistake.
After many tries, I tend to think that it's something about overalcheck()...
The append, clearelement and writeto are the additional mini functions and they are totally fine.
So, this script checks the form, and if everything is ok, opens a new page. However, if a field is empty or has a wrong type, it shows the relative error message (or a list of error messages).
I made a lot of variations, sometimes it opens without a completed form (like the code below), sometimes it shows the error message for 1 field only and then, and even if you complete all fields, it still doesnt open a new page.
I would appreciate your help.
<script>
function overallcheck ()
{
if(!checkname() || !checkemail() || !checkjob())
{
writeTo("problemArea","Error messages area");
if(!checkname())
writeTo("problemArea","Please insert a valid name");
if(!checkemail())
writeTo("problemArea","Please insert a valid email");
if(!checkjob())
writeTo("problemArea","Please insert your job");
return false;
}
return true;
}
function checkname()
{
clearElement("problemArea");
var fullname = document.forms['form'].fullname.value;
if (fullname.length == 0 || !isNaN(fullname))
return false;
}
function checkemail()
{
clearElement("problemArea");
var mail = document.forms['form'].Email.value;
if (mail == '' || mail.indexOf('#') == -1 || mail.indexOf('.') == -1)
return false;
}
function checkjob()
{
clearElement("problemArea");
var i;
for (i=0;i<4;i++)
{
if (document.forms['form'].job[i].checked) {return true;}
}
return false;
}
</script>
<body>
<form onsubmit="return overallcheck();" action="res.html" id=form target="_blank" method="GET">
<table>
<tr>
<td><b><p>blabla?</p></b> </td>
<td> <input type="text" name="fullname" size="20" placeholder="Enter a valid name"/> </td>
</tr>
<tr>
<td><b><p> E-mail: </p></b></td>
<td><input type="email" name="email" maxlength="15" size = "20" placeholder="Enter a valid email address"/> </td>
</tr>
<tr>
<p><td><b><p>bla?</td></p>
<td>1<input type="radio" name="job" value="gov" /><br/>
2<input type="radio" name="job" value="pri" /><br/><div id="problemArea"> </div>
3<input type="radio" name="job" value="unem" /><br/>
4<input type="radio" name="job" value="other" /><br/>
</td></tr>
</table>
<p>
<button type="submit" onclick="" >clickme</button>
</form>
</body>
</html>
Track each error type with it's own div. Wrap overallcheck in a try catch to and alert errors. This helped find the "Email" error.
function writeTo(id, msg) {
document.getElementById(id).innerHTML += "<p>" + msg + "</p>";
}
function clearElement(id) {
document.getElementById(id).innerHTML = "";
}
function overallcheck() {
try {
if (!checkname() || !checkemail() || !checkjob()) {
if (!checkname())
writeTo("problem_fullname", "Please insert a valid name");
if (!checkemail())
writeTo("problem_email", "Please insert a valid email");
if (!checkjob())
writeTo("problem_blah", "Please insert your job");
return false;
}
return true;
} catch (err) {
alert(err);
}
}
function checkname() {
clearElement("problem_fullname");
var fullname = document.forms['form'].fullname.value;
if (fullname.length == 0 || !isNaN(fullname)) {
return false;
}
return true;
}
function checkemail() {
clearElement("problem_email");
var mail = document.forms['form'].email.value; //Email.value;
if (mail == '' || mail.indexOf('#') == -1 || mail.indexOf('.') == -1) {
return false;
}
return true;
}
function checkjob() {
clearElement("problem_blah");
var i;
for (i = 0; i < 4; i++) {
if (document.forms['form'].job[i].checked) {
return true;
}
}
return false;
}
td {
vertical-align: text-top;
}
.problem {
color: red;
}
<form onsubmit="return overallcheck();" action="res.html" id=form target="_blank" method="GET">
<table>
<tr>
<td><b><p>blabla?</p></b>
</td>
<td>
<input type="text" name="fullname" size="20" placeholder="Enter a valid name" />
<div id="problem_fullname" class="problem"></div>
</td>
</tr>
<tr>
<td><b><p> E-mail: </p></b>
</td>
<td>
<input type="email" name="email" maxlength="15" size="20" placeholder="Enter a valid email address" />
<div id="problem_email" class="problem"></div>
</td>
</tr>
<tr>
<p>
<td><b><p>bla?</td></p>
<td>
1<input type="radio" name="job" value="gov" /><br/>
2<input type="radio" name="job" value="pri" /><br/>
3<input type="radio" name="job" value="unem" /><br/>
4<input type="radio" name="job" value="other" /><br/>
<div id="problem_blah" class="problem"> </div>
</td></tr>
</table>
<p>
<button type="submit" onclick="" >clickme</button>
</form>
Ok so I have this email sign up form that I use on my website. I got the script directly from the email management system as they are the ones that process the form.
I'm using it on my website and it works perfectly but when I try and run the same script in a Facebook App it fails to submit. Actually that's not strictly true as it does pop up with the 'You need to agree to the terms...' if left unchecked but it doesn't get any further than that.
I've tested it in a browser and it works so I know there's nothing wrong with the code, I'm just baffled as to why it won't function in Facebook.
Here is the script exactly how it appears on the page.
<form action="http://www.elabs12.com/functions/mailing_list.html" method="post" name="UPTml807" onSubmit="return (!(UPTvalidateform(document.UPTml807)));">
<input type="hidden" name="submitaction" value="3">
<input type="hidden" name="mlid" value="807">
<input type="hidden" name="siteid" value="2012000210">
<input type="hidden" name="tagtype" value="q2">
<input type="hidden" name="demographics" value="1,2,-1,40836,37592">
<input type="hidden" name="redirection" value="http://www.MYWEBISTE.com/WebContent/Promotions/PromotionsNewEmailThanks.htm">
<input type="hidden" name="uredirection" value="http://">
<input type="hidden" name="welcome" value="">
<input type="hidden" name="double_optin" value="">
<input type="hidden" name="append" value="on">
<input type="hidden" name="update" value="on">
<input type="hidden" name="activity" value="submit">
<div class="textfield">
<table border="0" cellspacing="0" cellpadding="5" width="100%">
<tr>
<td><span class="formText">Your First Name*</span><br/><input type="text" name="val_1" class="firstName" size="10" value="" /></td>
<td><span class="formText">Your Last Name*</span><br/><input type="text" name="val_2" class="lastName" size="10" value="" /></td>
</tr>
<tr>
<td colspan="2"><span class="formText">Your Email*</span><br/><input type='text' name='email' class="email" value='' style='display:block'/></td>
</tr>
<tr>
<td colspan="2"><span class="formText">Your Mobile Number</span><br/>
<input type='text' name='val_3' class="mobile" value='' style='display:block'/></td>
</tr>
<tr>
<td><div style="text-align:left; margin:0 0 20px 0px"><input type="checkbox" id="val_37592" name="val_37592" style="width:20px; height:10px;">
<span class="formText">I accept your Privacy Policy (below)*</span><br/><br/><span style="font-size:12px !important;" class="formText">*Required field</span></div></td>
<td align="right"><input type="submit" name="submit" value="Submit" class="submitBTN" /></td>
</tr>
</table>
</div>
<script language="Javascript">
function emailCheck (emailStr) {
var emailPat=/^(.+)#(.+)$/;
var specialChars="\\(\\)<>#,;:\\\\\\\"\\.\\[\\]";
var validChars="\[^\\s" + specialChars + "\]";
var quotedUser="(\"[^\"]*\")";
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
var atom=validChars + '+';
var word="(" + atom + "|" + quotedUser + ")";
var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
var matchArray=emailStr.match(emailPat);
if (matchArray==null) {
alert("Email address seems incorrect (check # and .'s)");
return false;
}
var user=matchArray[1];
var domain=matchArray[2];
if (user.match(userPat)==null) {
alert("The username doesn't seem to be valid.");
return false;
}
var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {
for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert("Destination IP address is invalid!");
return false;
}
}
return true;
}
var domainArray=domain.match(domainPat);
if (domainArray==null) {
alert("The domain name doesn't seem to be valid.");
return false;
}
var atomPat=new RegExp(atom,"g");
var domArr=domain.match(atomPat);
var len=domArr.length;
if ((domArr[domArr.length-1] != "info") &&
(domArr[domArr.length-1] != "name") &&
(domArr[domArr.length-1] != "arpa") &&
(domArr[domArr.length-1] != "coop") &&
(domArr[domArr.length-1] != "aero")) {
if (domArr[domArr.length-1].length<2 ||
domArr[domArr.length-1].length>3) {
alert("The address must end in a three-letter domain, or two letter country.");
return false;
}
}
if (len<2) {
var errStr="This address is missing a hostname!";
alert(errStr);
return false;
}
return true;
}
function UPTvalidateform(thisform)
{
if (document.getElementById("val_37592").checked==false){alert("Please let us know you have read and agree to the Terms and Conditions of this email alert sign up"); return(true);}
if (thisform.val_1.value==""){
alert("Please enter a value for First Name");
return(true);}if (thisform.val_2.value==""){
alert("Please enter a value for Last Name");
return(true);}
if (emailCheck(thisform.email.value))
{
if ((document.getElementById('unsubscribe')
&& document.getElementById('unsubscribe').checked) && (document.getElementById('showpopup') && document.getElementById('showpopup').value == "on")) {
alert('Thank you, now you are unsubscribed!');
}
else if(( (document.getElementById('unsubscribe')
&& !document.getElementById('unsubscribe').checked) || (!document.getElementById('unsubscribe')) ) && (document.getElementById('showpopup') && document.getElementById('showpopup').value == "on")){
alert('Thank you for signing up!');
}
return false;
}
else
{
return true;
}
}
</script>
</form>
I've tried removing the JS to see if Facebook was blocking it and I just get the same result. I've even tried submitting to a different URL but no luck.
Is there something I've missed/am I being blind? Or maybe it's a deeper issue...
Any help is much appreciated.
Thank you.
The url you submit to must be registred in the app details. Try changing the app domains in facebook developers.
Further more if you're browsing facebook in secure mode (default setting) it will block all content from non-ssl urls. so http://www.elabs12.com/functions/mailing_list.html would have to be https://www.elabs12.com/functions/mailing_list.html
I am only GCSE level and I need a text box in my code to only have 4 characters. I have made it a max of 4 but I need it to have a minimum of 4 aswell. I also made it only accept numbers. I am not using HTML 5 at my school.
This is my whole code:
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject. \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.ExamNumber.value=="") {
msg+="You must enter your exam number. \n";
document.ExamEntry.ExamNumber.focus();
document.getElementById('ExamNumber').style.color="red";
result = false;
}
if(document.ExamEntry.ExamNoLen.value.length <4) {
msg+="Your eaxm nuber must be 4 digits long. \n";
document.ExamEntry.ExamNumber.focus();
document.getElementById('ExamNumber').style.color="red";
result = false;
}
checkInput(elem){
if(elem.value.length != 4){
alert("This value needs to be 4 characters long!");
elem.value = ""; // Reset the textbox
}
else{
alert("This value is 4 characters long.");
}
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="ExamNumber">Exam Number </td>
<td>
<input name="ExamNumber" type="text"
onkeydown="return ( event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )"
maxlength="4" onblur="checkInput(this)" />
</td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" onClick="return validateForm();" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
Well you can't have a minlength because your users are going to need to type 1,2 and 3 characters to get to 4. (Unless you apply some sort of input mask which is more advanced). But you can check that it is 4 characters long when it is blurred..
<input name="ExamNumber" type="text" onblur="checkInput(this)" onkeydown="return ( event.ctrlKey || event.altKey || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false) || (95<event.keyCode && event.keyCode<106) || (event.keyCode==8) || (event.keyCode==9) || (event.keyCode>34 && event.keyCode<40) || (event.keyCode==46) )" maxlength="4" />
And then a simple JavaScript function..
function checkInput(elem){
if(elem.value.length != 4){
alert("This value needs to be 4 characters long!");
elem.value = ""; // Reset the textbox
}
else{
alert("This value is 4 characters long.");
}
}
This question already has answers here:
How can I validate an email address in JavaScript?
(79 answers)
Closed 8 years ago.
I am validating my form using javascript validation as whole validation is working fine but email validation is not working. My form code is as follows
<form method="post" action="contact.php" name="myForm" onsubmit="return validateForm()">
<h3>To know more contact us today.</h3>
<table>
<tr>
<td>Name:
<br />
<input id="name" name="name" type="text" />
</td>
</tr>
<tr>
<td>Contact No:
<br />
<input id="contact" name="contact" type="text" />
</td>
</tr>
<tr>
<td>Email:
<br />
<input id="email" type="text" name="email" />
</td>
</tr>
<tr>
<td>Address:
<br />
<textarea cols="34" id="address" name="address" type="text"></textarea>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
and my javascript code is as follows
<script type="text/javascript">
function validateEmail() {
var emailID = document.["myForm"]["email"].value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || (dotpos - atpos < 2)) {
alert("Please enter correct email ID")
document.myForm.email.focus();
return false;
}
return (true);
}
function validateForm() {
var x = document.forms["myForm"]["name"].value;
if (x == null || x == "") {
alert("First name must be filled");
return false;
}
var x = document.forms["myForm"]["contact"].value;
if (x == null || x == "" || isNaN(document.myForm.contact.value) || document.myForm.contact.value.length != 10) {
alert("Contact Number Must be 10 Digits");
return false;
}
var x = document.forms["myForm"]["email"].value;
if (x == null || x == "") {
alert("Email is must");
return false;
}
else {
var ret = validateEmail();
if (ret == false) {
return false;
}
}
var x = document.forms["myForm"]["address"].value;
if (x == null || x == "") {
alert("Address cannot be empty");
return false;
}
return (true);
}
</script>
var emailID = document.["myForm"]["email"].value;
^^
Syntax error. Dot-notation or Square-bracket-notation. Pick only one (per property).
I'm surprised that Firebug / Chrome Developer Tools / Dragonfly / etc didn't give you a clear pointer to that when you were testing.