Why the regular expression matches input but the alert still happens? - javascript

I made a simple page to validate input. but even my input matches the regular expressions, all three alerts still happen. Could you please help me figure it out? Thanks
<script>
function validate() {
var tel = document.getElementById("tel").innerHTML;
var email = document.getElementById("email").innerHTML;
var pcode = document.getElementById("pcode").innerHTML;
var tvalid = /^(\d{3}-\d{3}-\d{3}-\d{4})$/;
if(!tvalid.test(tel)) {
alert("Not a valid Phone Number");
}
if (!(/#gmail\.com$/.test(email)) && !(/#hotmail\.com$/.test(email)) && !(/#outlook\.com$/.test(email)) ) {
alert("Not a valid email");
}
var pvalid = /^([A-Z][A-Z]\d{2}-[a-z]\d[A-Z]\d)$/;
if(!pvalid.test(pcode)){
alert("Not a valid postal code.");
}
}
</script>
html
<label for="tel">Phone Number</label>
<input type="tel" id="tel" name="tel" placeholder="Format: 001-123-456-7890" required><br>
<input type="tel" id="tel" name="tel" placeholder="Format: 001-123-456-7890" required><br>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" placeholder="xxx#(gmail/hotmail/outlook).com" required><br>
<label for="pcode">Postal Code</label>
<input type="text" id="pcode" name="pcode" placeholder="AA11-c1V2"><br>
<button type = "button" id="submit" onclick="validate()">Validate</button>

The reason why your code returns invalid for all inputs is because youre not actually testing it against the entered input, rather an empty string ''.
.innerHTML will return an empty string since there is no HTML between the start and end of your input tags.
To get the value of a control try using something like var tel = document.getElementById("tel").value;
This will return the actual user input.
So your code should look like this:
function validate() {
var tel = document.getElementById("tel").value;
var email = document.getElementById("email").value;
var pcode = document.getElementById("pcode").value;
var tvalid = /^(\d{3}-\d{3}-\d{3}-\d{4})$/;
if (!tvalid.test(tel)) {
alert("Not a valid Phone Number");
}
if (!(/#gmail\.com$/.test(email)) && !(/#hotmail\.com$/.test(email)) && !(/#outlook\.com$/.test(email))) {
alert("Not a valid email");
}
var pvalid = /^([A-Z][A-Z]\d{2}-[a-z]\d[A-Z]\d)$/;
if (!pvalid.test(pcode)) {
alert("Not a valid postal code.");
}
}
<label for="tel">Phone Number</label>
<input type="tel" id="tel" name="tel" placeholder="Format: 001-123-456-7890" required><br>
<input type="tel" id="tel" name="tel" placeholder="Format: 001-123-456-7890" required><br>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" placeholder="xxx#(gmail/hotmail/outlook).com" required><br>
<label for="pcode">Postal Code</label>
<input type="text" id="pcode" name="pcode" placeholder="AA11-c1V2"><br>
<button type="button" id="submit" onclick="validate()">Validate</button>

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

re-enter email validator not working on javascript

So I'm trying to check if the user inputs the same email address and password twice in a signup form using javascript. It shouldn't let them sign up if they don't match, however only the portion of the passwords is working and the email isn't working. Here's my code:
<form>
<input type="email" name="fname" placeholder="Email Adress" required="required" class="input-txt" id="email1">
<input type="email" name="fname" placeholder="Confirm Email Adress" required="required" class="input-txt" id="email2">
<br><br>
<input id="password" type="password" name="fname" placeholder="Create Password" required="required" class="input-txt">
<input id="confirm_password" type="password" name="fname" placeholder="Confirm Password" required="required" class="input-txt"><br>
<button type="submit" class="btn">Sign up</button>
</form>
<script>
function validateMail() {
if(first_email.value != second_email.value) {
email2.setCustomValidity("Emails Don't Match");
} else {
email2.setCustomValidity('');
}
}
email1.onchange = validateMail;
email2.onkeyup = validateMail;
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
</script>
You need to assign var in top of the script:
var first_email = document.getElementById("email1")
, second_email = document.getElementById("email2")
, password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");

How to get this form validation script working

I have created a form and a form validation script that checks if all fields are filled in, the name and city fields contain only letters, the age and phone fields contain only numbers and if the entered email is a valid one. When used in the console, all of the statements work, but when I fill in every field, or fill in invalid values in the email field or phone number and age field, I still get an error message saying that the name and city field must contain only letters.
I have tried writing out every statement alone and also checking them one by one.
HTML & JS
<form>
<div class="form-group">
<label for="inputName">Name</label>
<input type="name" class="form-control" id="inputName" placeholder="Enter name">
</div>
<div class="form-group">
<label for="inputName">Age</label>
<input type="age" class="form-control" id="inputAge" placeholder="Enter age">
</div>
<div class="form-group">
<label for="inputCity">City</label>
<input type="city" class="form-control" id="inputCity" placeholder="Enter city">
</div>
<div class="form-group">
<label for="InputEmail1">Email address</label>
<input type="email" class="form-control" id="InputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<!-- <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> -->
</div>
<div class="form-group">
<label for="inputPhone">Phone number</label>
<input type="phone" class="form-control" id="inputPhone" placeholder="Phone number">
</div>
<button type="button" class="btn btn-primary submit">Submit</button>
<button type="button" class="btn btn-primary erase">Erase</button>
</form>
<script>
function validateForm() {
var name_cityRegex = /^[a-zA-Z]+$/;
var emailRegex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
var age_phoneRegex = /^\d+$/;
var nameValue = $('#inputName').val();
var cityValue = $('#inputCity').val();
var ageValue = $('#inputAge').val();
var phoneValue = $('#inputPhone').val();
var nameResult = name_cityRegex.test(nameValue);
var cityResult = name_cityRegex.test(cityValue);
var ageResult = age_phoneRegex.test(ageValue);
var phoneResult = age_phoneRegex.test(phoneValue);
var mailValue = $('#InputEmail1').val();
var mailResult = emailRegex.test(mailValue);
$(".btn.btn-primary.submit").click(function () {
$('.form-control').each(function () {
if ($(this).val() == "") {
$('.alert.alert-danger').show();
}
else if (nameResult == false || cityResult == false) {
$('.alert.alert-danger').text("Please use letters only in the fields 'Name' and 'City'");
$('.alert.alert-danger').show();
return false;
}
else if (ageResult == false || phoneResult == false) {
$('.alert.alert-danger').text("Please use digits only in the fields 'Age' and 'Phone number'");
$('.alert.alert-danger').show();
return false;
}
else if (mailResult == false) {
$('.alert.alert-danger').text("Please enter a valid email adress");
$('.alert.alert-danger').show();
return false
}
return true;
})
});
</script>
When I leave all fields empty the warning is ok. But when I do anything else I only get the warning that I can only use letters in the fields Name and City.
All help is greatly appreciated for a beginner!
I think you are failing to reassign the variables outside of the onClick function. I have tested below code and it works for me, i admit it is probably not a perfect solution reassigning all the variables each time and perhaps you could place some in global scope such as the RegEx statements. I also removed the loop as i don't think you need to loop over everything 5 times to check.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form>
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Enter name">
</div>
<div class="form-group">
<label for="inputName">Age</label>
<input type="text" class="form-control" id="inputAge" placeholder="Enter age">
</div>
<div class="form-group">
<label for="inputCity">City</label>
<input type="text" class="form-control" id="inputCity" placeholder="Enter city">
</div>
<div class="form-group">
<label for="InputEmail">Email address</label>
<input type="email" class="form-control" id="InputEmail" aria-describedby="emailHelp" placeholder="Enter email">
<!-- <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> -->
</div>
<div class="form-group">
<label for="inputPhone">Phone number</label>
<input type="phone" class="form-control" id="inputPhone" placeholder="Phone number">
</div>
<button type="button" class="btn btn-primary submit">Submit</button>
<button type="button" class="btn btn-primary erase">Erase</button>
</form>
<script>
$(".btn.btn-primary.submit").click(function () {
let name_cityRegex = /^[a-zA-Z]+$/;
let emailRegex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
let age_phoneRegex = /^\d+$/;
let nameValue = $('#inputName').val();
let cityValue = $('#inputCity').val();
let ageValue = $('#inputAge').val();
let phoneValue = $('#inputPhone').val();
let nameResult = name_cityRegex.test(nameValue);
let cityResult = name_cityRegex.test(cityValue);
let ageResult = age_phoneRegex.test(ageValue);
let phoneResult = age_phoneRegex.test(phoneValue);
let mailValue = $('#InputEmail').val();
let mailResult = emailRegex.test(mailValue);
if (nameValue == '' || cityValue == '' || ageValue == '' || phoneValue == '' || mailValue == '') {
$('.alert.alert-danger').show();
}
else if (nameResult === false || cityResult === false) {
$('.alert.alert-danger').text("Please use letters only in the fields 'Name' and 'City'");
$('.alert.alert-danger').show();
return false;
}
else if (ageResult == false || phoneResult == false) {
$('.alert.alert-danger').text("Please use digits only in the fields 'Age' and 'Phone number'");
$('.alert.alert-danger').show();
return false;
}
else if (mailResult == false) {
$('.alert.alert-danger').text("Please enter a valid email adress");
$('.alert.alert-danger').show();
return false
}
return true;
// })
});
</script>
</body>
</html>
I don't really know why your tests gives you an error, but I think your $('.form-control').each is useless.
In this foreach you test all your fields for each field.
Maybe try without this foreach, just test all your fields when you click on the button by removing this bit of code :
$('.form-control').each(function () {
if ($(this).val() == "") {
$('.alert.alert-danger').show();
}
})
I don't see any other problem.
You have a syntax error I corrected that check below code.
function validateForm() {
var name_cityRegex = /^[a-zA-Z]+$/;
var emailRegex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
var age_phoneRegex = /^\d+$/;
var nameValue = $('#inputName').val();
var cityValue = $('#inputCity').val();
var ageValue = $('#inputAge').val();
var phoneValue = $('#inputPhone').val();
var nameResult = name_cityRegex.test(nameValue);
var cityResult = name_cityRegex.test(cityValue);
var ageResult = age_phoneRegex.test(ageValue);
var phoneResult = age_phoneRegex.test(phoneValue);
var mailValue = $('#InputEmail1').val();
var mailResult = emailRegex.test(mailValue);
$('.form-control').each(function () {
if ($(this).val() == "") {
$('.alert.alert-danger').show();
}
else if (nameResult == false || cityResult == false) {
$('.alert.alert-danger').text("Please use letters only in the fields 'Name' and 'City'");
$('.alert.alert-danger').show();
return false;
}
else if (ageResult == false || phoneResult == false) {
$('.alert.alert-danger').text("Please use digits only in the fields 'Age' and 'Phone number'");
$('.alert.alert-danger').show();
return false;
}
else if (mailResult == false) {
$('.alert.alert-danger').text("Please enter a valid email adress");
$('.alert.alert-danger').show();
return false
}
return true;
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" name="name" class="form-control" id="inputName" placeholder="Enter name">
</div>
<div class="form-group">
<label for="inputName">Age</label>
<input type="text" name="age" class="form-control" id="inputAge" placeholder="Enter age">
</div>
<div class="form-group">
<label for="inputCity">City</label>
<input type="text" name="city" class="form-control" id="inputCity" placeholder="Enter city">
</div>
<div class="form-group">
<label for="InputEmail1">Email address</label>
<input type="text" name="email" class="form-control" id="InputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group">
<label for="inputPhone">Phone number</label>
<input type="text" name="phone" class="form-control" id="inputPhone" placeholder="Phone number">
</div>
<button type="button" class="btn btn-primary submit" onClick="validateForm()">Submit</button>
<button type="button" class="btn btn-primary erase">Erase</button>
</form>

How would it be possible to call multiple js functions to a single form?

Now when I run this code, the form's function do not run. Why, Im not sure. Is it because of the doall() function I placed in my js. I did it specifically to tell the button tag thats the function to ultimately run. Is placing functions within 1 whole function considered bad? Where did I go wrong with my javascript and html pairings? I am ultimately trying to have one part of the form validate with alerts, have the total spit a given value automatically after a radio is chosen, and as you click the submit button after everything is filled, it creates that var sign.
<form name="form1" action="" onsubmit="return doall{};">
<label for="fname">First Name:</label>
<input type="text" name="fname" id="fname" size="12" placeholder="First Name">
<label for="lname">Last Name:</label>
<input type="text" name="lname" id="lname" size="12" placeholder="Last Name">
<label for="address">Address:</label>
<input type="text" name="address" id="address" size="40" placeholder="Address">
<label for="city">City:</label>
<input type="text" name="city" id="city" size="40" placeholder="City">
<label for="state">State:</label>
<input type="text" name="state" id="state" size="40" placeholder="State">
<label for="country">Country:</label>
<input type="text" name="country" id="country" size="40" placeholder="Country">
<label for="zipcode">Zip Code:</label>
<input type="text" name="zipcode" id="zipcode" placeholder="Zip Code">
<p><label for="email">Email:</label>
<input type="text" name="email" id="email" size="30" placeholder="Email Address"></p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" size="20" placeholder="Password">
<p><label for="repass">Retype Password:</label>
<input type="password" name="repass" id= "repass" size="20" placeholder="Re-type Password"></p>
<p><b>Choose the Program you would like to purhase:</b></p>
<table align ="center">
<tr>
<td><input type="radio" name="offers" value= "Basic" id="chkbox" onchange="ontotal()"></td>
<td>Basic</td>
<td>$<span>19.99</span></td>
</tr>
<tr>
<td><input type="radio" name="offers" value= "Premium" id="chkbox" onchange="ontotal()" ></td>
<td>Premium</td>
<td>$<span >35.99</span></td>
</tr>
<tr>
<td><input type="radio" name="offers" value= "Super" id="chkbox" onchange="ontotal()"></td>
<td>Super</td>
<td>$<span >59.99</span></td>
</tr>
</table>
<p>
Total:
<input type="text" id="prototal" size="8" value="0" >
</p>
</form>
<button type="button" onclick="doall();">Submit</button>
<p id="submit"></p>
` function formval() {
var first = document.getElementById("fname")
var second = document.getElementById("lname")
var third = document.getElementById("address")
var fourth = document.getElementById("city")
var fifth = document.getElementById("state")
var sixth = document.getElementById("country")
var seventh = document.getElementById("zipcode")
var fire = document.getElementById("email")
var sense = document.getElementById("password")
var retype = document.getElementById("repass")
if (first == ""){
alert("Please enter first name");
return false;
}
if (second == ""){
alert("Please enter last name");
return false;
}
if (third == ""){
alert("Please enter address");
return false;
}
if(fourth == ""){
alert("Please enter city");
return false;
}
if (fifth == ""){
alert("Please enter state");
return false;
}
if (sixth == ""){
alert("Please enter county");
return false;
}
if (seventh == ""){
alert("Please enter zip code");
return false;
}
if (fire == ""){
alert("Please enter email address");
return false;
}
if (sense == ""){
alert("Please enter a password");
return false;
}
if (retype == ""){
alert("Please enter your typed password");
return false;
}
var sign = "Thank you for submission. Your purchase order instructions will be emailed shortly!";
document.getElementById("sub").innerHTML = sign;
}
var programprices = new Array();
programprices["Basic"]=19.99;
programprices["Premium"]=35.99;
programprices["Super"]=59.99;
function ontotal(){
var producttotal=0;
var calform = document.forms["form1"]
var offers = calform.elements["offers"]
for(var i = 0; i < offers.length; i++)
{
if (offers[i].checked)
{
producttotal = programprices[offers[i].value];
break;
}
}
return producttotal;
}
function caltotal(){
var price = ontotal;
var presentme = document.getElementById('prototal')
presentme.innerHTML = price
}
function doall(){
formval();
ontotal();
caltotal();
}
var form = document.getElementById('form1');
form.addEventListener('submit', formval);
form.addEventListener('submit', ontotal);
form.addEventListener('submit', caltotal); `
https://jsfiddle.net/Lnehnkaz/
First correct the above mentioned errors.
There is nothing wrong with calling some functions from another function. If you want multiple submit handlers, put the submit button within the form, change it to type="submit" and use the addEventListener method.
This works, when you give the form the attribute id="form1":
var form = document.getElementById('form1');
form.addEventListener('submit', formval);
form.addEventListener('submit', ontotal);
form.addEventListener('submit', caltotal);

Categories