Form validation not working in chrome nor firefox - javascript

Im working with this contact form.
<form name="contact" action="mailto:me#me.com&subject=subject&body=message"
onsubmit="return validate()" method="post" enctype="text/plain">
<label for="mail">Your mail address *</label>
<input type="text" name="mail"/></br></br>
<label for="subject">Subject *</label>
<input type="text" name="subject"/></br>
<label for="message">Your message *</label>
<textarea id="txtarea" name="message" form="contact"></textarea>
<input type="submit" value="Send"/>
</form>
And this javascript
function validateMail(mail) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(mail);
}
function validate(){
var x = document.forms["contact"];
if (x[0].value == null || x[0].value == ""){
alert("Your mail address");
return false;
}else{
if(!validateMail(x[0].value)){
alert("mail address not valid");
return false;
}
}
if(x[1].value == null || x[1].value == ""){
alert("Add a subject");
return false;
}
if(x['txtarea'].value.length < 1 || x['txtarea'].value == '' || x['txtarea'].value == null){
alert("Add your message");
return false;
}
}
This code works perfectly on IE11 (11.0.9600.18500) but chrome 54.0.2840.71 m (64-bit) and FF 49.0.2 just ignore my javascript and proceed to send the mail with empty fields or not valid info.
PS: im using id for the textarea since i cant find it with the form[#] option
Edit: I found that IE properly identifies the textarea as [object HTML TextAreaElement] but for both chrome and firefox is undefined

The problem is with your textarea, remove form="contact" from it. You can use the below form -
<form name="contact" action="mailto:me#me.com&subject=subject&body=message" onsubmit="return validate()" method="post" enctype="text/plain">
<label for="mail">Your mail address *</label>
<input type="email" name="mail" /></br>
</br>
<label for="subject">Subject *</label>
<input type="text" name="subject" /></br>
<label for="message">Your message *</label>
<textarea id="txtarea" name="message"></textarea>
<input type="submit" value="Send" />
</form>
And here is little optimized Javascript function for your form-
function validateMail(mail) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(mail);
}
function validate() {
var x = document.forms["contact"];
if (!x[0].value) {
alert("Your mail address");
return false;
} else {
if (!validateMail(x[0].value)) {
alert("mail address not valid");
return false;
}
}
if (!x[1].value) {
alert("Add a subject");
return false;
}
if (!x['txtarea'].value) {
alert("Add your message");
return false;
}
}

Managed to solve it by using:
if(document.getElementById('txtarea').value.length < 1 || document.getElementById('txtarea').value == '' || document.getElementById('txtarea').value == null)
instead of:
if(x['txtarea'].value.length < 1 || x['txtarea'].value == '' || x['txtarea'].value == null)
since neither chrome or firefox can properly process form['id']

Related

Form Validation in JQuery Mobile

I'm trying to add validation to the form I made
<fieldset>
<legend>ENTER YOUR INFORMATION HERE FOR DELIVERY</legend>
<form action="" name="deliveryform">
Name* :<input type="text" name="name" id="name">
Phone Number* : <input type="text" name="phonenumber" id="phonenumber">
<span id="warning1"></span>
Address* : <textarea name="address" id="address" required></textarea>
Email* : <input type="text" name="email" id="email">
<span id="warning2"></span>
<input type="submit" id="submitbutton" value="Submit" onsubmit=" return validation()">
</form>
</fieldset>
Javascript
function validation()
{
var name = document.getElementsByName("name").value;
var phonenumber =document.getElementsByName("phonenumber").value;
var email = document.getElementById("email").value;
var emailformat = "[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$";
if(name == ""|| null)
{
alert("Please Enter Your Name!");
return false;
}
if(isNaN (phonenumber))
{
document.getElementById("warning1").innerHTML ="Enter numbers only";
return false;
}
if(!email.match(emailformat))
{
document.getElementById("warning2").innerHTML="Please enter the correct format. Example : Abc1234#gmail.com"
return false;
}
else
{
alert("Submitted Successfully")
}
}
Nothing changed except ''Error Loading Page '' message appeared.
Did I miss something?
I thought coding in without and with Jquery in HTML is the same thing..

The onsubmit event handler javascript not working

I have a problem. When I clicked the submit button nothing happens, even when I filled out the username and password with numbers (I don't want the username and password contains any number so I did make the condition for it), there is no alert display. I do not know where the problem comes from? Can you guys help me with this
Note: the reset function works fine
function validateInput() {
var firstName = document.forms["sign_up"]["firstName"];
var lastName = document.forms["sign_up"]["lastName"];
var email = document.forms["sign_up"]["email"];
var reg = /^[a-zA-Z]+$/;
if (firstName.value !== '' || lastName.value !== '' || email.value !== '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
// return true;
return false; // for the demo, so it doesn't submit
} else {
if (firstName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in username";
return false;
} else if (lastName.value.match(reg) === false) {
document.getElementById("error").innerHTML = "Numbers are not allowed in password";
return false;
}
}
}
}
function reset() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("email").innerHTML = "";
}
<form id="sign_up" onsubmit="return validateInput()">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">Submit</button>
<button type="button" onclick="reset();">Cancel</button>
</form>
Use the Pattern attribute in input for validation like below
<input type="text" id="firstName" value="" pattern="[^0-9]*" title="Numbers are not allowed" placeholder="Enter your first name">
for more references: https://www.w3schools.com/tags/att_input_pattern.asp
And for reset functionality use reset
<input type="reset" value="reset">
It's better than create a special function for it and it saves your number of lines:-)
First, try to avoid to inline event handlers as they are not rec-emended at all. Also to reset form values you can simply use reset() method on the form.
Also, do not use innerHTML just to set the text of your error. You can use textContent instead which is better fit in your example.
You can use addEventListener with submit event to check for validation on your firstname and lastname.
I have fixed your code and its all working as expected.
Live Working Demo:
let form = document.getElementById("sign_up")
var firstName = document.getElementById("firstName")
var lastName = document.getElementById("lastName")
var email = document.getElementById("email")
var reset = document.getElementById("clearValues")
var reg = /^[a-zA-Z]+$/;
form.addEventListener('submit', function(e) {
e.preventDefault()
if (firstName.value != '' || lastName.value != '' || email.value != '') {
if (firstName.value.match(reg) && lastName.value.match(reg)) {
alert("Form is submitted");
} else if (!firstName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in username";
} else if (!lastName.value.match(reg)) {
document.getElementById("error").textContent = "Numbers are not allowed in password";
}
}
})
reset.addEventListener('click', function(e) {
document.getElementById("sign_up").reset();
})
input {
display:block;
}
<head>
</head>
<body>
<form id="sign_up" action="#">
<p id="error"></p>
<label for="firstName">First Name</label>
<input type="text" id="firstName" value="" placeholder="Enter your first name">
<label for="lastName">Last Name</label>
<input type="text" id="lastName" value="" placeholder="Enter your last name">
<label for="email">Email</label>
<input type="email" id="email" value="" placeholder="Enter your email">
<button type="submit">
Submit
</button>
<button type="button" id="clearValues" onclick="reset();">
Cancel
</button>
</form>
</body>
You don't need to return a function in onsubmit event. This should work fine.
<form id="sign_up" onsubmit="validateInput()">
Reference:
https://www.w3schools.com/jsref/event_onsubmit.asp

Validating multiple form boxes, javascript

I'm trying to make sure each field is filled in, else show an error. When I submit my form it goes through and no error is shown? Can anyone see whats wrong?
here is my form HTML
<form id="Form" name="Form" method: "post" action: '#' onsubmit="return validateForm()">
<fieldset>
<label>First name:*<br>
<input name="fname" id ="fname" type="text"></label><br>
<label>Last name:*<br>
<input name="lname" id="lname" type="text"></label><br>
<label>Email:*<br>
<input name="email" id="email" type="text"></label><br>
<label>Phone:<br>
<input name="phone" id="phone" type="text"></label><br>
<label>Message:*<br>
<input id="message" id="message" name="msg" type="text"></label><br>
<br>
<input name="submit" type="submit" value="send"><br>
</fieldset>
</form>
And here is my JS
function validateForm() {
var errormessage = "";
if (document.getElementbyID('fname').value == "") {
errormessage += "enter your first name /n";
document.getElementById('fname').style.borderColor = "red";
}
if (document.getElementbyID('lname').value == "") {
errormessage += "enter your last name /n";
document.getElementById('lname').style.borderColor = "red";
}
if (document.getElementbyID('email').value == "") {
errormessage += "enter your email /n";
document.getElementById('email').style.borderColor = "red";
}
if (document.getElementbyID('message').value == "") {
errormessage += "enter your message /n";
document.getElementById('message').style.borderColor = "red";
}
if (errormessage != "") {
alert(errormessage);
return false;
}
}
Open the Developer Tools in your browser. Look at the Console. Ensure that the "Preserve log" option is enabled so the errors are not lost when the form submits.
Uncaught TypeError: document.getElementbyID is not a function
JavaScript is case-sensitive. ID is not Id. You need to get the names of your function calls correct.
When your JS throws an exception, the function aborts, and form submission continues as normal.

Can not run document.getElementById

I just wrote a simple javascript to submit a form.
<div class=login>
<fieldset>
<legend>Login</legend>
<form id="form" method="get" action="summary_iframe.html" onsubmit="return validate()">
User: <input type="text" id="userAc" value="" name="userAc"><br>
Password: <input type="text" id="userPw" value="" name="userPw"><br>
This is the function, check that both user and password are not blank and there is no intervening space in use.
function validate(){
var userAc = document.getEmelentById('userAc').value;
var userPw = document.getEmelentById('userPw').value;
if(userAc.length == 0 || userPw.lenth == 0 || userAc.indexOf(' ')>-1 || userPw.indexOf(' ')>-1)
{
alert("Please input again!");
return false;
}
else
{
checkLogin(userAc, userPw);
return true;
}
}
But it does not work, I used a browser to debug and when it's running this line, it quits form the function.
var userAc = document.getEmelentById('userAc').value;
Please tell me what's wrong. Thanks!
Please alter your function as below.
function validate(){
var userAc = document.getElementById('userAc').value;
var userPw = document.getElementById('userPw').value;
if(userAc.length == 0 || userPw.lenth == 0 || userAc.indexOf(' ')>-1 || userPw.indexOf(' ')>-1)
{
alert("Please input again!");
return false;
}
else
{
checkLogin(userAc, userPw);
return true;
}
}
You need to use as document.getElementById('userAc').value, instead of document.getEmelentById('userAc').value. Hereafter please check your browser console before you post any question here. Thanks
You have missed Submit Button.
<form id="form" method="get" action="summary_iframe.html" onsubmit="return validate()">
User: <input type="text" id="userAc" value="" name="userAc"><br>
Password: <input type="text" id="userPw" value="" name="userPw"><br>
<input type="submit" value="submit" name="btnSubmit">
</form>

JavaScript Refreshes Instead of Changing Pages

I am unable to figure out why my page will not redirect to the set page. Whenever the condition is met, the page simply refreshes. I have gone into the browser console and pasted my redirect code, and it does redirect.
Full JavaScript Function:
function formSubmit(){
var formFN = document.getElementById("fName");
var formLN = document.getElementById("lName");
if( formFN.value.length == 0 || formFN.value == null){
window.alert("Please enter your first name.");
return false;
}
else if( formLN.value.length == 0 || formLN.value == null){
window.alert("Please enter your last name.");
return false;
}
else
{
document.location = "resultPage.html";
return false;
}
}
HTML Part:
<div id="form">
<form action="">
<h3>Thanks for visiting!</h3>
<label for="fName">First Name:</label>
<input type="text" id="fName" value="">
<br>
<label for="lName">Last Name:</label>
<input type="text" id="lName" value="">
<br>
<button onclick="formSubmit();">
Submit
</button>
<!-- <input type="submit" value="Submit" onclick="formSubmit();"> -->
</form>
</div>
By default, button elements have a type attribute of submit. Based on your question, you probably want this instead:
<button type="button" onclick="formSubmit();">
Submit
</button>
If you want a more general solution, you'd be better off capturing and handling the submit event on the form since things like pressing return in an input would trigger a submit as well.
window.addEventListener("load", function() {
document.getElementById("form").getElementsByTagName("form")[0].addEventListener("submit",function(event) {
event.preventDefault(); // Stop the normal action for this event
var formFN = document.getElementById("fName");
var formLN = document.getElementById("lName");
if( formFN.value == null || formFN.value.length == 0 ){
alert("Please enter your first name.");
}
else if( formLN.value == null || formLN.value.length == 0 ){
alert("Please enter your last name.");
}
else {
document.location = "resultPage.html";
}
});
});
<div id="form">
<form>
<h3>Thanks for visiting!</h3>
<label for="fName">First Name:</label>
<input type="text" id="fName" value="">
<br>
<label for="lName">Last Name:</label>
<input type="text" id="lName" value="">
<br>
<button>Submit</button>
</form>
</div>
Edit: It occurs to me that you should check for nulls before checking for length. (If .value is null then checking .value.length will throw an error.) Adjusted code accordingly.

Categories