I am adding a data validation to my code. I want to make sure the event title is not blank, and the zip code entered is valid. The javascript does not work. Can you tell me why?
<form name="form1" action="organize.php" onSubmit="return validateform1();" method="post" enctype="multipart/form-data">
<div class="form-element">
<label for="event_title">Event Title</label>
<input type="text" name="event_title" id="dob" />
</div>
<div class="form-element">
<label for="zip">Zip Code</label>
<input type="text" name="zip" id="dob" />
</div>
<script language="javascript">
function validateform1(){
var zipcode = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if(document.form1.event_title.value==""){
alert("Enter a title");
return false;
}
else if((!document.form1.zip.value.match(zipcode)){
alert("wrong zip format");
return false;
}
</script>
</form>
you have missed closing ) in this line:
else if((!document.form1.zip.value.match(zipcode)) {
should be :
else if((!document.form1.zip.value.match(zipcode))) {
or:
else if(!document.form1.zip.value.match(zipcode)) {
Always you should see browser console.you can see hint to get rid of your issues.
Probably doesn't help that your ZIP field has id="dob", but I think the main issue is that your function is missing a closing }, and your else if (( has an extra (. Try this:
function validateform1() {
var zipcode = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if (document.form1.event_title.value == "") {
alert("Enter a title");
return false;
} else if (!document.form1.zip.value.match(zipcode)) {
alert("wrong zip format");
return false;
}
}
Related
As i try to do javascript validation but it dosent work on click of submit button
my Js Code : validation.js which is inside resource/static/js/validate.js
function validate(){
var f=document.getElementById("form");
var hasEmailError = validateEmail(f);
if(!hasEmailError)
return false;
else
return true;
}
function validateEmail(form){
var error=document.getElementById("emailError");
var email=form["email"].value;
error.innerHTML="";
var regx = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|
(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-
Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if( email==null || email==""){
error.innerHTML="Input Your Email";
}
else if(!email.match(regx)){
error.innerHTML="Invalid Email";
}
if(error.innerHTML.length > 0)
return false;
else
return true;
}
my jsp code : registration.jsp
<script type="text/javascript" src="/js/validate.js"></script>
</head>
<body>
<form action="regUser" method="post" id="form">
First Name<input type="text" name="user_fname"><br>
Last Name<input type="text" name="user_lname"><br>
Email <input type="text" name="email"><br>
<font id="emailError" style="color: red;">${emailExistError} </font>
Contact No<input type="text" name="contactno"><br>
Password<input type="password" name="user_password"><br>
<input type="submit" onclick="return validate()" value="SUBMIT">
</form>
</body>
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/xxx?autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=pass#1234
spring.jpa.show-sql=true
spring.mvc.view.prefix=/WEB-INF/jsps/
spring.mvc.view.suffix=.jsp
server.servlet.context-path=/hotelmgmt
spring.main.allow-bean-definition-overriding=true
server.port = 8090
pls tell where am i missing the point?
You need put <script type="text/javascript" src="/js/validate.js"></script> before close body tag instead of head tag.
Put this line in one line.
var regx = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
Current code show error "Uncaught SyntaxError: Invalid regular expression: missing /"
I tried reproduce your code, it worked
function validate(){
var f=document.getElementById("form");
var hasEmailError = validateEmail(f);
if(!hasEmailError)
return false;
else
return true;
}
function validateEmail(form){
var error=document.getElementById("emailError");
var email=form["email"].value;
error.innerHTML="";
var regx = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if( email==null || email==""){
error.innerHTML="Input Your Email";
}
else if(!email.match(regx)){
error.innerHTML="Invalid Email";
}
if(error.innerHTML.length > 0)
return false;
else
return true;
}
<body>
<form action="regUser" method="post" id="form">
First Name<input type="text" name="user_fname"><br>
Last Name<input type="text" name="user_lname"><br>
Email <input type="text" name="email"><br>
<font id="emailError" style="color: red;"></font>
Contact No<input type="text" name="contactno"><br>
Password<input type="password" name="user_password"><br>
<input type="submit" onclick="return validate()" value="SUBMIT">
</form>
</body>
I think it would be helpful for you to first simplify the return statements.
The hasError = !false is very confusing.
Absolute newbie here - I'm super passionate about coding and just started with Javascript last week...I cannot seem to get this validation to work! Thanks in advance for all your good advice
-S
<script type="text/javascript">
//Registration Form Validation
function validate(){
var firstName=document.getElementById("name").value;
var maleUser = document.getElementById("maleButton").checked;
if(firstName=="" || firstName==" "){
alert("Please enter your first name: ");
return false;
}
else if(maleUser==false){
alert("Please select your gender: ");
}else{
return true; window.location.href="Search/index.htm";
</script>
<!-- Reg Form needing validation -->
<h1>Registration Form</h1>
<p>
<div class=form_settings>
<form name="RegForm" onsubmit="return(validate());" >
First name: <input type="text" name="first_name" id="name" placeholder="Enter your First name" size="35"/>
<br>
Gender:
<input type="radio" name="male" id="maleButton" value="male"> Male
<br>
</p>
</form>
Please correct your HTML code:
<h1>Registration Form</h1>
<div class="form_settings">
<form name="RegForm" action="search/index.htm">
First name:
<input type="text" name="first_name" id="name" placeholder="Enter your First name" size="35"/>
<br>
Gender:
<input type="radio" name="male" id="maleButton" value="male"> Male
<br>
<input type="submit" value="submit" onclick="return(validate());">
</form>
</div>
Add this updated JavaScript code:
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}
function validate(){
var firstName = document.getElementById("name").value;
var maleUser = document.getElementById("maleButton").checked;
if (trim(firstName) === ''){
alert("Please enter your first name: ");
return false;
}
else if(maleUser == false){
alert("Please select your gender: ");
return false;
}
else{
//window.location.href="Search/index.htm";
return true;
}
}
You can see a complete result here: https://jsfiddle.net/logual/ba5f7tkw/
Don't use window.location.href to submit form. Add an action attribute with url and a submit button to your form.
I ran your code and got
Uncaught SyntaxError: Unexpected end of input
on line 20
you're missing a } after your else
else{
return true; window.location.href="Search/index.htm";
Protip: Run in chrome and type CTRL-SHIFT-J
Hopefully this wont be quite as simple as I have been thinking it should have been. A simple HTML forum when submit is clicked calls a Javascript for validation to be handled by PHP to put the information that has been validated into a MySql table. The issue I am having is once i get the javascript return true, how do I pull this out to use in PHP?
The Forum:
<form action="" method="post" name="register">
<div class="field">
<label for "username">Username</label>
<input type="text" name="username" id="username" value="" autocomplete="off">
</div>
<div class="field">
<label for "password">Choose a password</label>
<input type="password" name="password" id="password">
</div>
<div class="field">
<label for "password_again">Reenter Password</label>
<input type="password" name="password_again" id="password_again">
</div>
<div class="field">
<label for "name">Name</label>
<input type="text" name="name" id="name" value="" autocomplete="off">
</div>
<input type="submit" value="Register" id="submit" onclick="validate()" />
The external JS file:
function validate() {
var password = document.register.password.value;
var passwordagain = document.register.password_again.value;
var name = document.register.username.value;
var test = new RegExp("[^a-zA-Z0-9]");
var space = String.fromCharCode(32);
if (name.match(test)) {
alert("Your name may only contain letters and numbers.");
return false;
} else if (name.match(space)) {
alert("Spaces are not allowed.");
return false;
} else if ((name.length <= 2) || (name.length >= 11)) {
alert("Name must be between 3 and 10 characters.");
return false;
} else if (!password.match(passwordagain)) {
alert("Passwords do not match");
return false;
} else if ((password.length <= 6) || (password.length >= 32)) {
alert("Password must be between 6 and 32 characters long.");
return false;
}
return true;
}
You can set the form's action attribute to point to a PHP page to be redirected to after the form has been validated.
Alternatively, you can use an XMLHttpRequest to send the form data to a PHP script. There was already a question asked on how to do this which you can find here.
Side Note:
It is usually a good idea to do all form validation server-side. This is because it is very easy for someone to hack JavaScript. Anyone could change your validate() function by opening up their browser's console and doing something like this:
validate = function() { return true; };
I am having issues with a code I am using to check email validity before sending it off to a database. I have a javascript code that checks the email in the following way:
See if the first email is a valid email address
See if the two email fields match
Here is the relevant parts of the form:
<form action="URLGOESHERE" method="post" name="someName" onSubmit="return validation();" id="formId">
<section class="sectionHeader">
<h2>Contact Information</h2>
<span class="important">*Required Fields</span>
</section>
<section id="contactInfo">
<fieldset>
<legend>Contact Information</legend>
<div id="contact">
<div class="inputGroupSameLine">
<label for="name" class="left"><span class="important">*</span>First Name:</label>
<input type="text" name="firstName" class="imp" size="20" maxlength="25" placeholder="John">
</div>
<div class="inputGroupSameLine">
<label for="name" class="left"><span class="important">*</span>Last Name:</label>
<input type="text" name="lastName" class="imp" size="20" maxlength="25" placeholder="Smith">
</div>
<div class="inputGroupSL">
<span class="left"><label for="org">Company/Group Name:</label></span>
<input type="text" name="org" size="30" maxlength="50" placeholder="Auburn University">
</div>
<div class="inputGroupSameLine">
<span class="left"><label for="email"><span class="important">*</span>Email:</label></span>
<input name='email' id='email' class="imp" type='text' size='45' maxlength='45' placeholder="youremail#example.com" />
</div>
<div class="inputGroupSameLine">
<span class="left"><label for="email2"><span class="important">*</span>Re-type Email:</label></span>
<input name='email2' id='email2' class="imp" type='text' size='45' maxlength='45' placeholder="youremail#example.com"/>
</div>
<div id="phoneGroup">
<span class="left"><span class="important">*</span>Phone #:</span>
<input name='phone' type='text' class="imp" id="phone" size='12' maxlength='20' placeholder="xxx-xxx-xxxx" />
</div>
<div id="extGroup">
<span class="left">Ext:</span>
<input name='ext' type='text' id="ext" size='12' maxlength='6' placeholder="xxxx" />
</div>
</div>
</fieldset>
</section>
And here is my code that runs onSubmit:
var reEMail=/^\w[\w\-\.]+\#\w[\w\-]+(\.[\w\-]+)+$/;
function validation() {
if (!checkImportant()) {
alert("Please enter information in all fields marked important.");
return false;
}
if (!checkAttendees())
return false;
if (!checkEmail($('#email'),$('#email2')))
return false;
return true;
}
function checkImportant() {
important = document.getElementsByClassName('imp');
for (i=0; i < important.length; i++) {
if($(important[i]).val() == "") {
$(important[i]).focus();
return false;
}
}
return true;
}
function checkAttendees() {
total = 0 + Number($('#numAttend').val());
parts = 0 + Number($('#8').val()) + 0 + Number($('#12').val()) + 0 + Number($('#16').val()) + 0 + Number($('#19').val()) + 0 + Number($('#26').val()) + 0 + Number($('#26').val()) + 0 + Number($('#55').val());
count = 0;
if (total != (parts)) {
alert('Please check to ensure you have entered the correct number of participants.');
count++;
if (count%2 == 0) {
$('#numAttend').focus();
return false;
}
else {
$('#8').focus();
return false;
}
}
return true;
}
function checkEmail(email,email2) {
if (goodEMail2(email)) {
if (email.val() != email2.val()) {
alert("Please check to make sure your email address is correct in both fields!");
email2.focus();
return false;
}
else return true;
}
else {
alert("Please input a valid email address");
setTimeout(function(){
$('#email').focus();
}, 100);
email.select();
return false;
}
return false;
}
function goodEMail2(field) {
return _checkIt2(reEMail, field);
}
function _checkIt2(re, field){
if (!re.test(field.val())) {
field.select();
field.focus();
return false;
}
else return true;
}
As you can see in my main if else statement of my checkEmail function I am having to use setTimeout to delay the focusing on the email field. If I take out the setTimeout, the page will not focus on the element. However, if I take out the setTimeout and change the specified element to the second email field, it works.
The only exception to this is in IE10 (to my testing in FF, Chrome, Safari, and IE10).
I don't really want to use this work around and I don't understand why I need to. Can anyone give me some ideas or answers?
Thanks!
EDIT: Can't seem to get my hack to work now. I'm not sure what it was doing before... so now focus() doesn't work at all on that particular element.
changing:
function checkImportant() {
important = document.getElementsByClassName('imp');
for (i=0; i < important.length; i++) {
if($(important[i]).val() == "") {
$(important[i]).focus();
return false;
}
}
return true;
}
to:
function checkImportant() {
important = document.getElementsByClassName('imp');
for (i=0; i < important.length; i++) {
if(important[i].value == "") { // drop the jQuery reference, not needed
important[i].focus(); // drop the jQuery reference, not needed
return false;
}
}
return true;
}
worked for me in Chrome
I'm been trying to validate my fields by using 'getElementById()' with '.value'. However, it seems like either getElementById.value is not working or some codes has overlap the function.
Updated Javascript function:
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") //wanted to check for alphabets only.
{
alert("Correct");
return true; //doesnt go to next.php
}
else
{
alert("Don leave blank!")
return false;
}
if (isNaN(Tel)) //check only numbers. Same code for FaxNo.
{
alert("Correct");
return true; //doesnt go to next.php
}
else
{
alert("invalid");
return false
}
return true; //doesn't go to next.php
}
My Form:
<Form action ="next.php" method="post">
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
<input type="submit" name="submit" onclick="return validate();"/>
</Form>
I have already defined my onclick function to my Javascript and tried to add return false too. But the alert still cant appear. Kindly advise.
Your markup is invalid:
<input name="Name" type="text" id="Name" " value=""/>
^-----------should be removed
so correction would be removing all extra " characters:
<input name="Name" type="text" id="Name" value=""/>
<input name="Name" type="text" id="Name" value=""/>
<input name="Tel" type="text" id="Tel" value=""/>
<input name="FaxNo" type="text" id="FaxNo" value=""/>
For preventing submition,when input is invalid, you can try something like a:
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") //wanted to check for alphabets only.
alert("Correct")
else {
alert("Don leave blank!")
return false;
}
if (isNumeric(Tel)) //check only numbers. Same code for FaxNo.
alert("Correct")
else {
alert("invalid");
return false;
}
}
//Borrowed from jQuery lib
function isNumeric( obj ){
return !isNaN( parseFloat(obj) ) && isFinite( obj )
}
<input type="submit" name="submit" onclick="return validate()"/>
Try this,
function validate() {
var Name = document.getElementById('Name').value;
var Tel = document.getElementById('Tel').value;
var FaxNo = document.getElementById('FaxNo').value;
if (Name != "") {}
else {alert("Don leave blank!"); return false;}
if (isNaN(Tel)){ alert("invalid"); return false;}
else { }
return true;
}
Your HTML submit button code should be
<input type="submit" name="submit" onclick="return validate()"/>
Use return false to prevent submitting form in case of any validation errors.