Post a form after javascript check - javascript

I would like to send a form after javascript validation in validateLengths() function.
If I fill a form action the form is send anyway if I don't specify javascript:void(0)
Here is my code so far...
Currently I'm just able to alert "submit form".
Sorry, I'm a noob in javascript.
Thank you for any related information.
Have a nice day.
Nicolas.
function validateLengths() {
let fnameCap = document.getElementById("firstName").value;
let lnameCap = document.getElementById("lastName").value;
if (fnameCap.length < 4 ) {
alert("First name must be atleast 4 characters. ");
return false;
}
if (lnameCap.length < 6) {
alert("Last name must be atleast 6 characters. ");
return false;
}
if(fnameCap.length >= 4 && lnameCap.length >= 6){
alert ("submit form"); // don't know how to send form here
}
}
function capitalize(){
let first = document.getElementById("firstName");
let last = document.getElementById("lastName");
let fcapitalized = first.value.toUpperCase();
let lcapitalized = last.value.toUpperCase();
first.value = (fcapitalized);
last.value = (lcapitalized);
validateLengths();
}
<form action="javascript:void(0)" id="theForm" title="form1">
<input name="firstName" type="text" id="firstName" value="At least 4 chars">
<br>
<input name="lastName" type="text" id="lastName" value="At least 6 chars">
<br>
<input type="submit" name="submit" id="submit" value="Submit" onClick="javascript:capitalize()">
</form>

Related

Multiple Form Validation in JS using Class

I want to validate 2 html forms - First form is on the FAQ page and the second form is on the contact us page. Both forms have name and phone as common input fields so I want to validate both form conveniently in JS by using Class.
My JS code is as follows for validating Name and Phone input field for FAQ form.
class FormValidate {
constructor(nameField, phoneField, emailField, form) {
this.nameField = nameField; // name input field
this.phoneField = phoneField; // phone input field
this.emailField = emailField; // email input field
this.form = form;
}
// method for validation of name input
validateName(nameField) {
const regName = new RegExp("^[a-zA-Z\\s]*$");
let isNameValid = false;
let name_z = nameField.value.trim(); // input value of Name input field
let isNameHasValidLength = name_z.length < 3 || name_z.length > 20 ? false : true;
// Name input field is not empty and contain proper data -> Not Empty && value must be between 3 to 20 characters && follow reg expression for validation
if( !(name_z === '') && isNameHasValidLength && (regName.test(name_Z)) ){
isNameValid = true;
}
return isNameValid;
}
validatePhone(phoneField) {
let isPhoneValid = false;
let phone_z = phoneField.value.trim(); // input value of Phone input field
let isPhoneHasValidLength = phone_z.length < 10 || phone_z.length > 13 ? false : true; // making sure that phone number is between 10 to 13 digits -> +91 and rest 10 digits
const regPhone = new RegExp("^([0|+[0-9]{1,5})?([7-9][0-9]{9})$");
// Validating Phone Number -> Not Empty && Must have 10 to 13 digits only && follow reg expression for validation
if( !(phone_z === '') && isPhoneHasValidLength && regPhone.test(phone)) {
isPhoneValid = true;
}
return isPhoneValid;
}
}
let faqForm = new FormValidate(document.querySelector('#name'), document.querySelector('#phone'), null, document.querySelector('#faq-form'));
faqForm.form.addEventListener('submit', function(e) {
let nameOkay;
let phoneOkay;
let submitOkay;
nameOkay = faqForm.validateName(faqForm.nameField);
phoneOkay = faqForm.validatePhone(faqForm.phoneField);
submitOkay = nameOkay && phoneOkay;
// Prevent form submission if form input is not okay
if (!submitOkay) {
e.preventDefault();
}
});
HTML form code -
<form id="faq-form" action="mail-faq.php" method="POST">
<div class="faq-form-group"> <span class="faq-form-span-text">Name</span>
<input type="text" placeholder="i.e, John Smith" name="name" id="name" autocomplete="off" required>
</div>
<div class="faq-form-group"><span class="faq-form-span-text">Phone</span>
<input type="text" placeholder="+91 123456789" name="phone" id="phone" autocomplete="off" required>
</div>
<div class="faq-form-group"><span class="faq-form-span-text">Message</span>
<textarea placeholder="Your question" name="message" id="message" autocomplete="off" required></textarea>
</div>
<div class="faq-form-group">
<button class="faq-form-submit-btn" id="submit" type="submit" name="submit">Submit </button>
</div>
</form>
The problem is that nameField.value.trim(); and phoneField.value.trim(); statements are returning value - "" Which makes the validation false.
How can I fix this problem?
When you correct the typo here in (regName.test(name_Z)) (lowercase z) then the trimed vars are as expected (not "")...

email validation accept two dot just in the form

my problem is I want The email should have no spaces in it and the domain name should be either two words separated by a ‘.’ or three words separated by two dots e.g. username#abc.efg.xy.
and not acceptable to more than three dot
<form name="myForm" onsubmit="return validateForm()" method="post" >
Name: <input type="text" name="fname" placeholder="Name">
<br>
Email: <input type="text" name="femail" placeholder="saleh#gmail.com">
<br>
Message: <input class="filed" type="text" size="60" style="height:200px">
<br>
Age : <input type="text" name="fage" placeholder="between 10 and 120">
<br>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["femail"].value;
var z = document.forms["myForm"]["fage"].value;
if (x == "" || x == null || y == "" || z == null) {
alert("You must be filled out");
return false;
}
if (isNaN(z) || z < 10 || z > 120) {
alert("the age should be between 10 and 120 ");
return false;
}
if (!y.includes('#') ) { // i do not how to complete the if condition
alert("The emali not include # or more one . ");
return false;
}
}
</script>
your're in for a ride
You can use a regular expression to test if the input is an email, NOTE the following answer tests true to 99.9% of the email addresses, but could still fail
const emailReg = new RegExp(/^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.){1,2}[a-zA-Z]{2,}))$/)
if (emailReg.test(y)){
//do something if the email is indeed an email
}
I added some examples in a regex validator https://regex101.com/r/vJ7A3N/1/
source: https://emailregex.com/
you could also use <input type="email" id="email" name="email">

Make Javascript write on page after submit button pressed

Here is a bit of code I have sourced from w3schools which shows that whenever a name is over 10 characters, the page should add a bit of text, in this case, it should add on "hi", but instead, it removes everything from the page and goes onto a new page and only displays "hi". How can I resolve this?
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php" onsubmit="return myFunction()">
Name (max 10 characters): <input type="text" id="fname" size="20" name="fname"><br>
Age (from 1 to 100): <input type="text" id="age" size="20" name="age"><br>
E-mail: <input type="text" id="email" size="20" name="mail"><br><br>
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
var at = document.getElementById("email").value.indexOf("#");
var age = document.getElementById("age").value;
var fname = document.getElementById("fname").value;
submitOK = "true";
if (fname.length > 10) {
document.write("hi");
}
if (isNaN(age) || age < 1 || age > 100) {
alert("The age must be a number between 1 and 100");
submitOK = "false";
}
if (at == -1) {
alert("Not a valid e-mail!");
submitOK = "false";
}
if (submitOK == "false") {
return false;
}
}
</script>
</body>
</html>
Simply put, don't use document.write(). If you read the nice orange text at the top of the documentation, you'll see why:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
document.write() should only be used while a page is loading, to ouput while it's creating the webpage, and should not be used afterwards. Consider creating a div, and writing to there instead:
function myFunction() {
var at = document.getElementById("email").value.indexOf("#");
var age = document.getElementById("age").value;
var fname = document.getElementById("fname").value;
submitOK = "true";
if (fname.length > 10) {
document.getElementById('result').innerHTML = 'Fname is > 10!';
}
if (isNaN(age) || age < 1 || age > 100) {
alert("The age must be a number between 1 and 100");
submitOK = "false";
}
if (at == -1) {
alert("Not a valid e-mail!");
submitOK = "false";
}
if (submitOK == "false") {
return false;
} else {
alert('Submitted Successfully!');
return false; // Returning false here just for SO Code Snippet
}
}
<form action="/action_page.php" onsubmit="return myFunction()">
Name (max 10 characters): <input type="text" id="fname" size="20" name="fname"><br>
Age (from 1 to 100): <input type="text" id="age" size="20" name="age"><br>
E-mail: <input type="text" id="email" size="20" name="mail"><br><br>
<input type="submit" value="Submit">
<div id="result"></div>
</form>
Additionally, I notice you're setting submitOK = "true". Javascript does have booleans (See this also). Why not use that instead?
submitOK = true;
if (fname.length < 10) {
alert('Your name should be more than 10 characters');
submitOK = false;
}
if (submitOK) { // Same as "if (submitOK == true)"
//Good to go
}

Issues in add validate email in javascript

Here is my code:
<form method="post" name="form1" action="invitation_enrollv5.asp?action=1" onSubmit="return GetTextValue()">
<input style="float:right;" id="nextbutton" name="" type="submit" value="Next" />
</form>
May i know, how and where can i add validate script to validate input email address.
If i blank or invalid id means it shows error states.
Can anyone help me? thanks in advance.
For input boxes, you can specify the type as email, and the browser will validate for you.
<input type="email" required>
Or for javascript:
function validate(emailString) {
return /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(emailString)
}
This will return true if the value for the emailString parameter is a valid email.
Lets assume you have an input field in your HTML as such -
<form name="emailForm">
<input type="email" id="email" name="email" />
</form>
In your javascript you can then add an event handler whenever a user activates
the text field and then clicks elsewhere (or uses tab to navigate to the next field)
$('#email').blur(function() {
// Instead of .blur() you can also just have the
// form submit event use the checkEmail() function.
checkEmail();
});
function checkEmail(){
var email = document.forms["emailForm"]["email"].value;
var atnum = email.replace(/[^#]/g, '').length
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || email.length <= dotpos + 2 || atnum > 1) {
// E-mail was not valid
$('#email').css({border: '1px solid #e74c3c'});
alert("Not a valid e-mail address");
setTimeout( function() {
$('#email').css({border: '1px solid #555'});
}, 800);
} else {
// E-mail was OK
alert("You're good to go!");
}
}
Here's a fiddle

Why is return false not keeping my form from submitting?

http://jsfiddle.net/1z9Lr5rv/1/
I am creating a contact form for my website. I thought it was working fine, but it always submits the form, wether or not there's an error, where return false should keep the form from submitting.
I'm sorry if this is really obvious and dumb, but I'm very new to this sort of thing . . .
The form works fine if you take it out of JS Fiddle (you should post the code here anyway). Here it is (with the redundant parts removed):
<div class="body">If you have any questions about me, my teaching or curriculum, etc., please don't hesitate to contact me here. Please fill out all the fields in this form..
<br>
<br>
<form name="contact-me" class="contact-me" onsubmit="return warnsub(this)"
method="POST"
action="https://secure.mailjol.net/allforms/u/3dcdda44.php" autocomplete="off">
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname">
Email Address: <input type="text" name="email">
Message: <textarea name="message" id="message"></textarea>
<input type="submit" value="Send">
</form>
</div>
<script>
function warnsub(form) {
var error = [];
var fname = form.fname;
var lname = form.lname;
var email = form.email;
var message = form.message;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (fname.value == "") {
error.push(fname);
}
if (lname.value == "") {
error.push(lname);
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
error.push(email);
}
if (message.value == "") {
error.push(message);
}
if (error.length) {
for (i = 0; i < error.length; i++) {
// You want to clear this class if the user has another
// attempt and gets it right
error[i].className = 'error';
}
error[0].focus();
return false;
}
return true;
}
You need to handle the event object that is automatically passed into the submit handler and call preventDefault().
Example:
var myForm = document.forms["contact-me"];
myForm.onsubmit = function(e)
{
if(!warnsub())
{
e.preventDefault();
}
}
As #Pointy has commented: IE9 does not automatically pass the event object to the onsubmit delegate. Discussion of how to shiv this is outside the scope of this question.
But just a side note - its good to try and avoid function calls in inline html (e.g. <form onsubmit=//your function() /> calls. Your Google-Fu can teach you why.

Categories

Resources