Validating a form for ONLY letter inputs - javascript

Im validating a form but im struggling to get it to only accept letters for firstname and lastname fields
hope u can help
heres my code:
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstname", "lastname", "email"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
onlyletters = "Only letters allowed.";
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Only Letters.
if (!/^([a-zA-Z])+$/.test(errornotice.val())) {
errornotice.addClass("needsfilled");
errornotice.val(onlyletters);
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});

Should this line be testing against errornotice.val() or firstname.val()?
if (!/^([a-zA-Z])+$/.test(errornotice.val())) {
// Maybe this is what you intended.
// This requires adding some more variables earlier when you set email and errornotice
email = $("#email");
errornotice = $("#error");
// Add vars for first/lastname
firstname = $("#firstname");
lastname = $("#lastname");
if (!/^([a-zA-Z])+$/.test(firstname.val())) {
firstname.addClass("needsfilled");
firstname.val(onlyletters);
}
// then do the same for lastname
if (!/^([a-zA-Z])+$/.test(lastname.val())) {
lastname.addClass("needsfilled");
lastname.val(onlyletters);
}
However, your regex of letters only is going to eliminate a lot of valid names including apostrophes, diacritics, umlauts, etc.

Related

if element is not blank add another element to the list of required element before submit

Hi all how could I insert a (if) statement to this code that if (element1) value is not blank then (element2) is required before submitting.
I'm already using a list of validated element that needs to be filled before subtitling
I would like to add a few more to that list depending on if some element are not empty.
Here's part of the code I'm not sure how or where to inset the if statement.
function submitBotton() {
var tool1 = document.getElementById("OtherEquipment1").value
if (tool1 !== '') {
toolowner1: "Equipment Owner is required!",
}
var toValidate = {
prefDate: "Date is required!",
Person: "Name is required!",
Loc: "Location is required!",
Time: "Time is required!",
};
var idKeys = Object.keys(toValidate);
var allValid = true;
idKeys.forEach(function(id) {
var isValid = checkIfValid(id, toValidate[id]);
if (!isValid) {
allValid = false;
}
});
if (allValid) {
addRecord();
}
}
Thanks

How to Validate a Form using the Functions I created

I have created functions to validate my form. But I want them all to run at once when I click the submit button. So, I have a formValidate function, and then I have a firstNameValidate, lastNameValidate ect.
My question is, how would I create the formValidate function to run the functions i have, but ONLY submit the form if all of them are true?
function firstNameValidate() {
// Making sure that the firstname input is not blank
if (firstName.value.length == 0) {
// If the firstname input is blank, then return the error text below
error.innerHTML = 'Please Enter a Valid First Name, Cannot be Blank';
// Error text css class
error.className = 'error';
// Making sure that the browser window focuses on the error
firstName.focus();
// Does not let the browser submit the form
// this statement makes sure that the input has only letters
return false;
} else if (!firstName.value.match(letter)) {
// // If the input has something other then numbers, show this error.
error.innerHTML =
'Please Enter a Valid First Name, Cannot contain characters(!##) or numbers';
// // error text css class
error.className = 'error';
// browser window focuses on error
firstName.focus();
// Form does not submit
return false;
}
if (firstName.value.length > 0 && firstName.value.match(letter)) {
error.className = '';
error.innerHTML = '';
return true;
}
}
I can get the first name and last name to validate, however if one them is filled out it sends the form. So the return true and return false I think are wrong.
function firstNameValidate() {
if (firstName.value.length == 0) {
error.innerHTML = 'Please Enter a Valid First Name, Cannot be Blank';
error.className = 'error';
firstName.focus();
return false;
}
if (!firstName.value.match(letter)) {
error.innerHTML = 'Please Enter a Valid First Name, Cannot contain characters(!##) or numbers';
error.className = 'error';
firstName.focus();
return false;
} else {
//intended code goes here , or simply return true.
}
}
If you want to do strict checking then write all the validation in if statement, and if everything is filled properly then do the correct code in an else statement,
and call the above function on form onsubmit or on a button click it will do the work..
Hope this helps ..!!

Form validation by country value

I have a query form with a country list. Mobile number and e-mail validation are working fine when the country India is selected, but when the user selects another country, I need mobile number validation off. Here is the code for validation:
<script type="text/javascript">
$(document).ready(function() {
$("#submitfeedback").click(function() {
var email = $("#fdbk_email").val();
var enqMobileNo= $("#fdbk_num").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (email == '' || enqMobileNo == '')
{
$("#returnmessage").append("<span>Enter your vaild E-mail & Mobile No.<span>");
return false;
}
var mailPattern = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!mailPattern.test(email))
{
$("#returnmessage").append("<span>Enter your valid email address!<span>");
return false;
}
var phoneNumberPattern = /^[0-9]{10}$/;
if(!phoneNumberPattern.test(enqMobileNo))
{
$("#returnmessage").append("<span>Enter your 10 digits mobile no only.<span>");
return false;
}
});
});
</script>
If I understand correct that you don't want to check mobile no when country is not India then I assumed your country is a dropdown field with id "country" then you can do following:
if($('#country option:selected').val() == 'india')
{
var phoneNumberPattern = /^[0-9]{10}$/;
if(!phoneNumberPattern.test(enqMobileNo))
{
$("#returnmessage").append("<span>Enter your 10 digits mobile no only.<span>");
return false;
}
}
Please update id selector and value accordingly

JavaScript button doesn't work

I am very new to using JavaScript so bear with me. I only finished the different courses found on Codecademy so far.
So I'm trying to make a sign up form for a website where you need a user. I found a pretty cool one on the internet that I changed a bit and also made use of the Datepicker from jQuery. It looks like this:
I got code to check whether the user filled out the different fields but it doesn't seem to work. In my index.html file I included the following file:
<script src="js/signupsubmit.js"></script>
And at the bottom of the form I do this:
<div>
<p id="sign_user" onClick="Submit()">Sign Up</p>
</div>
So good so far. In the JavaScript I have the following code:
function Submit() {
var emailRegex = /^[A-Za-z0-9._]*\#[A-Za-z]{2,5}$/;
var fname = document.form.Name.value,
lname = document.form.LastName.value,
femail = document.form.Email.value,
freemail = document.form.enterEmail.value,
fpassword = document.form.Password.value,
dateObject = $("#datepicker").datepicker(
{
onSelect: function()
{
var dateObject = $(this).datepicker('getDate');
}
});
if( fname == "") {
document.form.name.focus();
document.getElementById("errorBox").innerHTML = "Enter First Name";
return false;
}
if( lname == "" )
{
document.form.LastName.focus() ;
document.getElementById("errorBox").innerHTML = "Enter Last Name";
return false;
}
if (femail == "" )
{
document.form.Email.focus();
document.getElementById("errorBox").innerHTML = "Enter your Email Address";
return false;
}else if(!emailRegex.test(femail)){
document.form.Email.focus();
document.getElementById("errorBox").innerHTML = "Enter a Valid Email Address";
return false;
}
if (freemail == "" )
{
document.form.enterEmail.focus();
document.getElementById("errorBox").innerHTML = "Re-enter the Email Address";
return false;
}else if(!emailRegex.test(freemail)){
document.form.enterEmail.focus();
document.getElementById("errorBox").innerHTML = "Re-enter a Valid Email Address";
return false;
}
if(freemail != femail){
document.form.enterEmail.focus();
document.getElementById("errorBox").innerHTML = "The Email Addresses don't Match!";
return false;
}
if(fpassword == "")
{
document.form.Password.focus();
document.getElementById("errorBox").innerHTML = "Enter a Password";
return false;
}
if(dateObject == null) {
document.form.datepicker.focus();
document.getElementById("errorBox").innerHTML = "Please Enter a Birthday";
}
}
I am a bit shaky on trying to read the Datepicker too. But otherwise, can you possibly spot what might be missing in this puzzle? When I press the blue "Sign Up" button, literally nothing happens. I can provide more info if needed.
You have a mistake addressing the form: The correct formula is not document.form, but document.forms[0]. Or even better, I recommend you to give the form a specific unique name, and address it by that name:
HTML:
<form name="mydata">...</form>
Javascript:
var fm=document.forms.mydata
Also, take care of lowercase/uppercase lettering: Identifiers in Javascript are case-sensitive, which means that the input "Name" must be always addressed as "Name" (you mispelled that identifier in the line document.form.name.focus()).

Remaking jQuery form validation

I am trying to remake a jQuery script by (http://jorenrapini.com/blog/javascript/the-simple-quick-and-small-jquery-html-form-validation-solution). This script is checking if a from is filled, if not a error message will appear.
What I want to do is to only get the error message when one of two form input-fields are filled out, if none of them are then they should be ignored. The form fields are named "firstinput" and "secondinput" (you can see their id in the code).
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstinput", "secondinput"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
Can anybody please help me with a solution, I would really appreciate it.
/A girl that spend a LOT of time solving this without luck :(
I would wrap your for loop in a conditional that evaluates if one or the other has a value.
if($("#field1").val() == "" && $("#field2").val() == ""){
//Ignore
}else{
//Do something
}
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstinput", "secondinput"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
if($("#firstinput").val() != "" || $("#secondinput").val() != "")
{
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});

Categories