My javascript form validation is working correctly. I want it so that when the form is valid, it will go to a different page. I am having trouble with that part. I tried using the document object to submit it if everything is valid but its not working
Javascript:
function func(){
var first = document.getElementById('fname').value;
var last = document.getElementById('lname').value;
var email = document.getElementById('mail').value;
var phone = document.getElementById('phone').value;
var val_phone = /^\(\d{3}\)\d{3}-\d{4}$/;
var val_mail = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
if ( first == "" || last == "" || email == "" || phone == "")
{
alert("Do not Leave Any Blank Answers");
return;
}
if ( phone != phone.match(val_phone) || email != email.match(val_mail) )
{
alert("Incorrect Format! \n Please Check Email and Phone Number! ");
return;
}
else {
document.forms["survey"].sumbit();
}
}
HTML:
<form id="survey" name="survey" action="SlideShow.html" method="post">
First Name:<br>
<input type="text" id="fname" name="fname" required="required"><br>
Last Name:<br>
<input type="text" id="lname" name="lname" required="required"><br>
Email:<br>
<input type="email" id="mail" name="mail" required="required"><br>
Phone Number:<br>
<input type="text" id="phone" name="phone" required="required"><br><br>
<input type="button" value="Submit" onclick="func()">
</form>
Your else block is calling sumbit(), but the proper spelling is submit().
Additionally, I recommend getting in the habit of a strict === check as opposed to a ==.
Here's a JSFiddle with the updated and refactored code:
http://jsfiddle.net/cyeof94g/
Related
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..
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
I have an input field whereby the user has to enter a phone number and it has to be exactly 10 numbers. My script isn't working and I'm wondering how to specify the 'exactly 10' part. At the moment it's just less than 10.
var contact_number = document.getElementById('number');
input = contact_number.value
if (input.length = 10){
alert("The field needs to contain 10 numbers!")
return false
}else {
return true
}
if (contact_number == ""){
alert("You need to enter a Phone Number")
return false;
}
<hr>
<!-- Clients details -->
<p>Contact Person: <input id="contact" name="contact" type="text" placeholder="Type Full Name here"></p>
<p>Contact Number: <input id="number" name="number" type="number" maxlength="10" placeholder="Type Number here"></p>
<p>Email address: <input id="email" name="email" type="email" placeholder="Type Email here"></p>
<hr>
You can use the not equal operator !=
var contact_number = document.getElementById('number');
input = contact_number.value
if (input.length != 10){
alert("The field needs to contain 10 numbers!")
return false
}else {
return true
}
if (contact_number == ""){
alert("You need to enter a Phone Number")
return false;
}
<hr>
<!-- Clients details -->
<p>Contact Person: <input id="contact" name="contact" type="text" placeholder="Type Full Name here"></p>
<p>Contact Number: <input id="number" name="number" type="number" maxlength="10" placeholder="Type Number here"></p>
<p>Email address: <input id="email" name="email" type="email" placeholder="Type Email here"></p>
<hr>
It looks like your first if-statement is off. I think you want it to say not equals. What you have currently is not a comparison, and will always go into the body of the if statement.
if (input.length != 10){
alert("The field needs to contain 10 numbers!")
return false
}
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.
for my nic input,the no. of characters should be equal to 14 which i already did and the first character should be equal to the first letter in Lastname. how am i suppose to put this validation.
<form name="form" onsubmit="return formValidation()" action="submit.html">
lastname :<input type="text" name="lastname" id="lastname">
</input><br><br>
<label>NIC Number:</label>
<input type="text" name="NIC" id="NIC" pattern="[0-9]{14}" maxlength="14"></input></br></br>
<input id="submit" type="submit" name="submit" id="submit">
You can add a custom validation: JSFiddle
Code
function validateNIC() {
var nic = document.getElementById("NIC").value;
var lname = document.getElementById("lastName").value;
var valid = true;
if (nic.length != 14) {
console.log("Length must be 14 characters");
} else if (nic[0] != lname[0]) {
console.log("First Character of both input should be same");
}
else{
console.log("Valid")
}
}
<input type="text" id="lastName">
<input type="text" id="NIC" maxlength=14>
<button onclick="validateNIC()">validate</button>
try like this using charAt.
var x = 'some string';//value from first field
var y="s2324343353";//value from nic
if(x.charAt(0) == y.charAt(0)){
alert("first character is same");
}// alerts 's'
I have modified pattern to accept first character as alphanumeric. Then following function should help you validate the first character mismatch validation.
function formValidation() {
var ln = document.getElementById("lastname");
var nic = document.getElementById("NIC");
if (ln.value.substr(0, 1) != nic.value.substr(0, 1)) {
alert("NIC first character not acceptable.");
return false;
} else {
return true;
}
}
<form name="form" onsubmit="return formValidation()" action="submit.html">
lastname :
<input type="text" name="lastname" id="lastname">
</input>
<br>
<br>
<label>NIC Number:</label>
<input type="text" name="NIC" id="NIC" pattern="[a-zA-Z0-9][0-9]{13}" maxlength="14"></input>
</br>
</br>
<input id="submit" type="submit" name="submit" id="submit">
function formValidation() {
var lastname = $('#lastname').val();
var NIC = $('#NIC').val();
if (lastname.charAt(0) != NIC.charAt(0)) {
return false;
}