There is a problem with my Javascript form validation where I'm trying to return true or false values but it is not working.It only returns the first if/else statements (whether it is true or false) and from there it doesn't work.Once you see the javascript code, you should understand what I am trying to do.
$('#button').click(function(){
name = $("#name").val(); //name input
age = $("#age").val(); //age input
sex = $("#sex").val(); // sex input
if(name.match(/(\w)\s(\w)/)){
return true;
}
else {
$('.form-row:first-child').css('border','1px solid red');
return false;
}
if (age < 0 || age > 130 || isNaN(age)) {
$('.form-row:nth-child(2)').css('border','1px solid red');
return false;
}
else {
return true;
}
if (sex == "male" || sex == "Male" || sex == "female" || sex == "Female"){
return true;
}
else {
$('.form-row:nth-child(3)').css('border','1px solid red');
return false;
}
});
Return will break out of the function. Instead, set a flag and return that flag at the end.
$('#button').click(function(){
returnFlag = false
name = $("#name").val(); //name input
age = $("#age").val(); //age input
sex = $("#sex").val(); // sex input
if(name.match(/(\w)\s(\w)/)){
returnFlag = true;
}
else {
$('.form-row:first-child').css('border','1px solid red');
returnFlag = false;
}
if (age < 0 || age > 130 || isNaN(age)) {
$('.form-row:nth-child(2)').css('border','1px solid red');
returnFlag = false;
}
else {
returnFlag = true;
}
if (sex == "male" || sex == "Male" || sex == "female" || sex == "Female"){
returnFlag = true;
}
else {
$('.form-row:nth-child(3)').css('border','1px solid red');
returnFlag = false;
}
return returnFlag;
});
Related
I've been trying to validate USA and Canadian postal codes as I'm sending them through an api. However, I can't seem to get the regex to work. My validation is a bit messy but it should work nonetheless, I believe the regex is correct I just have the wrong logic? I would appreciate any help. Thanks.
function checkoutv2() {
var typepostal;
if (xcountry == 1) {
//canada
typepostal = "Canada";
} else if (xcountry == 2) {
//usa
var typepostal = "USA";
}
console.log(xcountry);
var xfirstname = document.getElementById("firstname").value;
var xlastname = document.getElementById("lastname").value;
var xemail = document.getElementById("email").value;
var xcity = document.getElementById("city").value;
var xaddress = document.getElementById("address").value;
var xpostal = document.getElementById("postal").value;
xpostal = xpostal.toString().trim();
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var ca = new RegExp(/([ABCEGHJKLMNPRSTVXY]\d)([ABCEGHJKLMNPRSTVWXYZ]\d){2}/i);
var us = new RegExp("^\\d{5}(-{0,1}\\d{4})?$");
if (xfirstname == "" || xfirstname.length > 50) {
document.getElementById("firstname").style.border = "1px solid red";
} else if (xlastname == "" || xlastname.length > 50) {
document.getElementById("lastname").style.border = "1px solid red";
} else if (reg.test(xemail) == false || xemail.lenth > 100) {
document.getElementById("email").style.border = "1px solid red";
} else if (xcity == "" || xcity.length > 100) {
document.getElementById("city").style.border = "1px solid red";
} else if (xaddress == "" || xaddress.length > 100) {
document.getElementById("address").style.border = "1px solid red";
} else if (
typepostal == "Canada" &&
ca.test(xpostal.toString().replace(/\W+/g, "")) == false &&
xpostal.length >= 10
) {
console.log("postal is cad");
console.log(xpostal);
document.getElementById("postal").style.border = "1px solid red";
} else if (
typepostal == "USA" &&
xpostal.length > 10 &&
us.test(xpostal.toString()) == false
) {
console.log("postal is us");
document.getElementById("postal").style.border = "1px solid red";
} else {
checkout();
}
}
I want to insert the records into the database(MySQL) but before insertion i want to validate the form fields whether they are filled by users or not, It must be validate onclick of submit button and i am inserting the records using the annotation method which is related to a java file so, when i am trying to insert the records using spring annotation method and validating the records in JavaScript it gives me the following Error:
HTTP Status 500 - Request processing failed; nested exception is java.lang.NumberFormatException: For input string: ""
My javaScript:
<script type="text/javascript">
function validateFields()
{
var c_name = document.formregisterclinic.ctl00$cphMaster$txtClinicName.value;
var p_no = document.formregisterclinic.ctl00$cphMaster$txtPhone.value;
var st_address = document.formregisterclinic.ctl00$cphMaster$txtStreetAddress.value;
var state = document.formregisterclinic.ctl00$cphMaster$txtState.value;
var city = document.formregisterclinic.ctl00$cphMaster$txtCity.value;}
var zip_code = document.formregisterclinic.ctl00$cphMaster$txtZipCode1.value;
var f_name = document.formregisterclinic.ctl00$cphMaster$txtCPFName.value;
var l_name = document.formregisterclinic.ctl00$cphMaster$txtCPLName.value;
var email = document.formregisterclinic.ctl00$cphMaster$txtEmail.value;
var cell_no = document.formregisterclinic.ctl00$cphMaster$txtCellPhone.value;
var u_name = document.formregisterclinic.ctl00$cphMaster$txtUserName.value;
var pass = document.formregisterclinic.ctl00$cphMaster$txtPassword.value;
var c_pass = document.formregisterclinic.ctl00$cphMaster$txtConfirmPassword.value;
if(c_name == "" || c_name == null)
{
alert("Clinic name can't be blank");
return false;
}
else if(p_no == "" || p_no == null)
{
alert("Phone number can't be blank");
return false;
}
else if(st_address == "" || st_address == null)
{
alert("Street address can't be blank");
return false;
}
else if(state == "" || state == null)
{
alert("State can't be blank");
return false;
}
else if(city == "" || city == null)
{
alert("City can't be blank");
return false;
}
else if(zip_code == "" || zip_code == null)
{
alert("Zip code can't be blank");
return false;
}
else if(f_name == "" || f_name == null)
{
alert("First name can't be blank");
return false;
}
else if(l_name == "" || l_name == null)
{
alert("Last name can't be blank");
return false;
}
else if(email == "" || email == null)
{
alert("Email can't be blank");
return false;
}
else if(cell_no == "" || cell_no == null)
{
alert("Cell number can't be blank");
return false;
}
else if(u_name == "" || u_name == null)
{
alert("User name can't be blank");
return false;
}
else if(pass == "" || pass == null)
{
alert("Password can't be blank");
return false;
}
else if(c_pass == "" || c_pass == null)
{
alert("Confirm password can't be blank");
return false;
}
</script>
My mapping method:
#RequestMapping(value = "/registerclinic", method = RequestMethod.POST)
public String registerclinicdbconnection(Locale locale, Model model, HttpServletRequest req, HttpServletResponse res)throws ServletException
{
String clinic_name = req.getParameter("ctl00$cphMaster$txtClinicName");
long phone_no = Long.parseLong(req.getParameter("ctl00$cphMaster$txtPhone"));
String street_add = req.getParameter("ctl00$cphMaster$txtStreetAddress");
String state = req.getParameter("ctl00$cphMaster$txtState");
String city = req.getParameter("ctl00$cphMaster$txtCity");
int zip_code = Integer.valueOf(req.getParameter("ctl00$cphMaster$txtZipCode1"));
String first_name = req.getParameter("ctl00$cphMaster$txtCPFName");
String last_name = req.getParameter("ctl00$cphMaster$txtCPLName");
String email = req.getParameter("ctl00$cphMaster$txtEmail");
long cell_phone = Long.parseLong(req.getParameter("ctl00$cphMaster$txtCellPhone"));
String user_name = req.getParameter("ctl00$cphMaster$txtUserName");
String password = req.getParameter("ctl00$cphMaster$txtPassword");
String c_password = req.getParameter("ctl00$cphMaster$txtConfirmPassword");
// Inserting records to register the clinic by making connection with database.
String queryText = "insert into registerclinic(clinicname,phone,streetadd,state,city,zipcode,firstname,lastname,email,cellphone,username,password) values('"+clinic_name+"','"+phone_no+"','"+street_add+"','"+state+"','"+city+"','"+zip_code+"','"+first_name+"','"+last_name+"','"+email+"','"+cell_phone+"','"+user_name+"','"+password+"')";
try
{
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/clinicmanagement","root","dipak");
Statement stat = con.createStatement();
stat.executeUpdate(queryText);
System.out.println("Record has been inserted");
stat.close();
con.close();
return "success";
}catch(Exception ea)
{
System.out.println("Exception Occured.."+ ea);
return "fail";
}
}
seems as though you don't have a return true at the end of your validateFields() method
try below:
function validateFields()
{
var c_name = document.formregisterclinic.ctl00$cphMaster$txtClinicName.value;
var p_no = document.formregisterclinic.ctl00$cphMaster$txtPhone.value;
var st_address = document.formregisterclinic.ctl00$cphMaster$txtStreetAddress.value;
var state = document.formregisterclinic.ctl00$cphMaster$txtState.value;
var city = document.formregisterclinic.ctl00$cphMaster$txtCity.value;}
var zip_code = document.formregisterclinic.ctl00$cphMaster$txtZipCode1.value;
var f_name = document.formregisterclinic.ctl00$cphMaster$txtCPFName.value;
var l_name = document.formregisterclinic.ctl00$cphMaster$txtCPLName.value;
var email = document.formregisterclinic.ctl00$cphMaster$txtEmail.value;
var cell_no = document.formregisterclinic.ctl00$cphMaster$txtCellPhone.value;
var u_name = document.formregisterclinic.ctl00$cphMaster$txtUserName.value;
var pass = document.formregisterclinic.ctl00$cphMaster$txtPassword.value;
var c_pass = document.formregisterclinic.ctl00$cphMaster$txtConfirmPassword.value;
if(c_name == "" || c_name == null)
{
alert("Clinic name can't be blank");
return false;
}
else if(p_no == "" || p_no == null)
{
alert("Phone number can't be blank");
return false;
}
else if(st_address == "" || st_address == null)
{
alert("Street address can't be blank");
return false;
}
else if(state == "" || state == null)
{
alert("State can't be blank");
return false;
}
else if(city == "" || city == null)
{
alert("City can't be blank");
return false;
}
else if(zip_code == "" || zip_code == null)
{
alert("Zip code can't be blank");
return false;
}
else if(f_name == "" || f_name == null)
{
alert("First name can't be blank");
return false;
}
else if(l_name == "" || l_name == null)
{
alert("Last name can't be blank");
return false;
}
else if(email == "" || email == null)
{
alert("Email can't be blank");
return false;
}
else if(cell_no == "" || cell_no == null)
{
alert("Cell number can't be blank");
return false;
}
else if(u_name == "" || u_name == null)
{
alert("User name can't be blank");
return false;
}
else if(pass == "" || pass == null)
{
alert("Password can't be blank");
return false;
}
else if(c_pass == "" || c_pass == null)
{
alert("Confirm password can't be blank");
return false;
}
return true;
}
I want to validate my form, if any of the input field is blank, the error warning will show beside the blank input field. The error message must be comes out all at one time for the blank input, not show one by one. How to do this?
Below is my javascript code :
function doValidate()
{
var x=document.forms["form"]["fullname"].value;
if (x==null || x=="")
{
document.getElementById('error1').innerHTML="Full name is required!";
return false;
}
var y=document.forms["form"]["uid"].value;
if (y==null || y=="")
{
document.getElementById('error2').innerHTML="Username is required!";
return false;
}
var z=document.forms["form"]["pwd"].value;
if (z==null || z=="")
{
document.getElementById('error3').innerHTML="Password is required!";
return false;
}
var a=document.forms["form"]["pwd2"].value;
if (a==null || a=="")
{
document.getElementById('error4').innerHTML="Please re-enter your password!";
return false;
}
var pwd = document.getElementById("pwd").value;
var pwd2 = document.getElementById("pwd2").value;
if(pwd != pwd2){
alert('Wrong confirm password!');
return false;
}
var b=document.forms["form"]["role"].value;
if (b==null || b=="Please select...")
{
document.getElementById('error5').innerHTML="Please select user role!";
return false;
}
}
You should start your function with var ok = true, and in each if-block, instead of having return false, you should set ok = false. At the end, return ok.
Here's what that might look like:
function doValidate() {
var ok = true;
var form = document.forms.form;
var fullname = form.fullname.value;
if (fullname == null || fullname == "") {
document.getElementById('error1').innerHTML = "Full name is required!";
ok = false;
}
var uid = form.uid.value;
if (uid == null || uid == "") {
document.getElementById('error2').innerHTML = "Username is required!";
ok = false;
}
var pwd = form.pwd.value;
if (pwd == null || pwd == "") {
document.getElementById('error3').innerHTML = "Password is required!";
ok = false;
}
var pwd2 = form.pwd2.value;
if (pwd2 == null || pwd2 == "") {
document.getElementById('error4').innerHTML = "Please re-enter your password!";
ok = false;
} else if (pwd != pwd2) {
document.getElementById('error4').innerHTML = "Wrong confirm password!";
ok = false;
}
var role = form.role.value;
if (role == null || role == "Please select...") {
document.getElementById('error5').innerHTML = "Please select user role!";
ok = false;
}
return ok;
}
(I've taken the liberty of changing to a more consistent formatting style, improving some variable-names, simplifying some access patterns, and replacing an alert with an inline error message like the others.)
I am having a hard time trying to do a correct form validation. I have Name, Email, and Phone Number fields. I implemented the validation check for all of them and when I click on the submit query, it returns email as false, but not anything else. It also will still submit the form. How do I fix this?
JSFiddle: http://jsfiddle.net/GVQpL/
JavaScript Code:
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
return false;
}
else if(fullNameV.indexOf(" ") <= fullNameV.length)
{
alert("Not a valid name");
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
return false;
}
var atpos = emailV.indexOf("#");
var dotpos = emailV.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
{
alert("Not a valid e-mail address");
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
error = alert("You didn't enter a phone number.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (isNaN(parseInt(stripped)))
{
error = alert("The phone number contains illegal characters.\n");
phoneNumberV.style.background = 'Yellow';
}
else if (!(stripped.length == 10))
{
error = alert("The phone number is the wrong length. Make sure you included an area code.\n");
phoneNumberV.style.background = 'Yellow';
}
return error;
}
Update your fiddle's html for the function to be called onsubmit="return validateForm()" and removed the required="required" changed your function to work, you can see it here:
http://jsfiddle.net/GVQpL/3/
function validateForm(/*fullName, email, phoneNumber*/)
{
//-------------------------NAME VALIDATION-----------------------------//
var fullNameV = document.forms["queryForm"]["fullName"].value;
if (fullNameV == null || fullNameV == "")
{
alert("Name must be filled out!");
document.forms["queryForm"]["fullName"].focus();
return false;
}
else if(fullNameV.indexOf(" ") >= fullNameV.length)
{
alert("Not a valid name");
document.forms["queryForm"]["fullName"].focus();
return false;
}
//-------------------------EMAIL VALIDATION-----------------------------//
var emailV = document.forms["queryForm"]["email"].value;
if (emailV == null || emailV == "")
{
alert("Email must be filled out!");
document.forms["queryForm"]["email"].focus();
return false;
}
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(emailV)){
alert("Not a valid e-mail address");
document.forms["queryForm"]["email"].focus();
return false;
}
//-------------------------PHONE # VALIDATION-----------------------------//
var phoneNumberV = document.forms["queryForm"]["phoneNumber"].value;
if (phoneNumberV == null || phoneNumberV == "")
{
alert("Phone Number must be filled out!");
document.forms["queryForm"]["phoneNumber"].focus();
return false;
}
var error = "";
var stripped = phoneNumberV.replace(/[\(\)\.\-\ ]/g, '');
if (phoneNumberV == "")
{
alert("You didn't enter a phone number.\n");
document.forms["queryForm"]["phoneNumber"].focus()
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (isNaN(parseInt(stripped)))
{
alert("The phone number contains illegal characters.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
else if (!(stripped.length == 10))
{
alert("The phone number is the wrong length. Make sure you included an area code.\n");
document.forms["queryForm"]["phoneNumber"].focus();
document.forms["queryForm"]["phoneNumber"].style.background = 'Yellow';
return false;
}
if(!confirm('Are you sure you want to submit your DSLR query?')){
return false;
}
return true;
}
The radio validation works but then the rest don't. What have I done wrong?
function validateRadio(radios) {
for (i = 0; i < radios.length; ++i) {
if (radios[i].checked) return true;
}
return false;
}
function validateForm() {
if (validateRadio(document.forms["pancettaForm"]["updateShip"])) {
return true;
} else {
alert("Please tell us how you would like to update your order.");
return false;
}
}
var x = document.forms["pancettaForm"]["order-number"].value;
if (x == null || x == "") {
alert("Please provide your order number.");
return false;
}
var x = document.forms["pancettaForm"]["full-name"].value;
if (x == null || x == "") {
alert("Please provide your full name, or the recipients name if you are updating shipping information.");
return false;
}
var x = document.forms["pancettaForm"]["phone"].value;
if (x == null || x == "") {
alert("Please provide a phone number in case of delivery questions.");
return false;
}
var display = document.getElementById('address').style.display;
if (display == 'block') {
var x = document.forms["pancettaForm"]["address"].value;
if (x == null || x == "") {
alert("Please provide your address.");
return false;
}
}
var display = document.getElementById('city').style.display;
if (display == 'block') {
var x = document.forms["pancettaForm"]["city"].value;
if (x == null || x == "") {
alert("Please provide your city.");
return false;
}
}
var display = document.getElementById('state').style.display;
if (display == 'block') {
if (document.pancettaForm.state.value == "- Select State -") {
alert("Please provide your state.");
return false;
}
}
var display = document.getElementById('zip').style.display;
if (display == 'block') {
var x = document.forms["pancettaForm"]["zip"].value;
if (x == null || x == "") {
alert("Please provide your zip code.");
return false;
}
}
var display = document.getElementById('newShipDate').style.display;
if (display == 'block') {
if (document.pancettaForm.state.value == "- Select Date -") {
alert("Please choose your new shipping date.");
return false;
}
}
Just reverse the test so you do not have to return
if(!validateRadio (document.forms["pancettaForm"]["updateShip"]))
{
alert("Please tell us how you would like to update your order.");
return false;
}
// continue
You had the end bracket after the test of the radios so the rest of the script just floated in cyberspace
Also return true only once at the end and do not have var x multiple times and be consistent in how you access the form elements and I also fixed your date test which was testing state
function validateForm() {
var x,display,form = document.forms["pancettaForm"];
if (!validateRadio(form["updateShip"])) {
alert("Please tell us how you would like to update your order.");
return false;
}
x = form["order-number"].value;
if (x == null || x == "") {
alert("Please provide your order number.");
return false;
}
x = form["full-name"].value;
if (x == null || x == "") {
alert("Please provide your full name, or the recipients name if you are updating shipping information.");
return false;
}
x = form["phone"].value;
if (x == null || x == "") {
alert("Please provide a phone number in case of delivery questions.");
return false;
}
display = form["address"].style.display;
if (display == 'block') {
x = form["address"].value;
if (x == null || x == "") {
alert("Please provide your address.");
return false;
}
}
display = form["city"].style.display;
if (display == 'block') {
x = form["city"].value;
if (x == null || x == "") {
alert("Please provide your city.");
return false;
}
}
display = form['state'].style.display;
if (display == 'block') {
x = form['state'].value;
if (x == "- Select State -") {
alert("Please provide your state.");
return false;
}
}
display = form['zip'].style.display;
if (display == 'block') {
x = form["zip"].value;
if (x == null || x == "") {
alert("Please provide your zip code.");
return false;
}
}
display = form["newShipDate"].style.display;
if (display == 'block') {
x = form["newShipDate"].value;
if (x.value == "- Select Date -") {
alert("Please choose your new shipping date.");
return false;
}
}
return true;
}