I have some input fields, which I want to validate directly as the user is typing
The input fields are bind to certain conditions though.
Here is the example:
<input type="text" data-type="inputFullName" />
<br />
<input type="text" data-type="inputEmail" />
<br />
<input type="text" data-type="inputPhone" />
<br / >
<input type="checkbox" id="chkbox" />
<label>Check here</label>
<br />
<button id="button1" disabled>Click</button>
And the JS:
$('input').on('keyup change', function () {
$('#button1').prop('disabled', $('input[data-type="inputFullName"]').val() == '' || $('input[data-type="inputEmail"]').val() == '' || $('input[data-type="inputPhone"]').val() == '' || !$('input[type="checkbox"]').is(':checked'))
});
So far so good, but how can I check for:
1) user has entered full name (first+lastname)
2) email is actually an email
3) phonenumber is 8 numbers long
I have made an JSFiddle
Any help is appreciated.
Email validation can be done by this:
Validate email address in JavaScript?
phonenumber:
<input type="text" id="inputPhonenumber" >
js:
var phonenumber = document.getElementById("inputPhonenumber").value;
if(phonenumber.length == 8)
return true;
else
return false;
These questions have been answered before. And they are not that hard to find here.
Related
I am trying to disable all other inputs within a specific form "<form id="join">"
if the user has not first filled out the <input type="text" id="userkey" name="userkey" /> input and all other inputs will remain disabled until the "<form id="join">" input has been filled out.
The reason for this is to model user behavior so they will join our site discord first for various reasons that I won't be going into. I understand that this is not a secure method. All user data will be sanitized and validated on the server side to protect the site/database. I understand that it is possible to bypass this and still submit data, again user data will be sanitized and validated on the server side to protect the site/database. I am doing thise because even with a huge note on the membership form to do so, they still try to submit data and bypass joining the discord making it difficult to communicate with them. this is an attempt at idiot proofing a site - also it blocks a lot of spam as spambots generally can't join a discord.
here is a very simple example from which I will extrapolate to our actual membership form.
here is the htmt
<form id="join-membership">
user key
<br />
<input type="text" id="userkey" name="userkey" />
<br />
<p>If you do not have a user key, please join our discord to get one</p>
Email
<br />
<input type="email" id="email" disabled="disabled" />
<br />
Username
<br />
<input type="text" id="username" name="username" disabled="disabled" />
<br />
Password
<br />
<input type="password" id="pass" name="password" disabled="disabled" />
<br />
Confirm Password
<br />
<input type="password" id="pass2" name="password2" disabled="disabled" />
<br />
About You
<br />
<textarea id="about" name="about" disabled="disabled"></textarea>
<br />
<input type="submit" id="submit" value="Register" disabled="disabled" />
</form>
<div id="test"></div>
here is the JavaScript
<script>
(function() {
$('form > input').keyup(function() {
var email = true;
var empty = false;
$('form > input').each(function() {
if ($(this).val() == '') {
empty = true;
}
});
if (email == empty) {
$('#register').attr('disabled', 'disabled');
} else {
$('#register').removeAttr('disabled');
}
});
})()
</script>
Please note that I am super new to JavaScript and the web and have researched and found script to disable the submit button, but our form is a bit complex and I don't want users to try to fill it out as to find out the can't submit it even if they failed to read the instruction. This is model user behavior to provide what I hope is a better user experience in the long term.
Thank you for any help given.
Hi you can try something like this
(function() {
$("#userkey").keyup(function() {
const userkey = this.value;
if (userkey) {
$('.other-inputs input, .other-inputs textarea').removeAttr('disabled');
} else {
$('.other-inputs input, .other-inputs textarea').attr('disabled', 'disabled');
}
});
})()
on user key input change, the function is checking if there is value in userkey input if exist It will remove disabled attribute from the inputs that are in div other-input
Check here for an example: https://jsfiddle.net/t4ub0xs3/
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have already searched the site and while I found similar issues, I couldn't get the answer I needed, so I am asking now. I need to validate a contact form, the PHP validation is very simple but works on a base level, I want to supplement this with browser validation through JS but it is not working, the JS validation does not trigger or is not correctly coded.
I'm working on this page: http://camp-tags.com/?main_page=contact
Thanks in advance for looking for me.
The function is supposed to loop through and make sure that the 4 elements are not empty, and that both variables for phonenumber and email are formatted correctly. If any flag as false, the error is supposed to be pushed to an array and then all errors output in a single alert.
Below is the code. (updated using the tips given here. No validation at all now.)
*update: I found one glaring error I can not believe I missed. I didn't have a closing tag on the , now that is done, the form will not send unless you input the phone correct but is not validating the rest and no Alert is being issued to advise what is wrong?
JS:
function validateForm(event){
var form1 = document.getElementById("form1"),
phone = document.getElementById("phonenumber").value,
email = document.getElementById("email").value,
name = document.getElementById("name").value,
address = document.getElementById("address").value,
tomatch = /^\d{3}-\d{3}-\d{4}$/,
emailMatch = /^\[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[A-Z]{2,4}$/;
var errors = [];
if (phone){
event.preventDefault();
errors.push("The Phone Number is required.");
return false;
} else if (tomatch.test(phone)){
return true;
} else {
event.preventDefault();
errors.push("The phone number must be formated as follows: XXX-XXX-XXXX.");
return false;
}
if (name === null || name === " "){
event.preventDefault();
errors.push("The Name is required.");
return false;
} else {
return true;
}
if (email === null || email === " "){
event.preventDefault();
errors.push("The email is required.");
return false;
} else if (emailMatch.test(email)){
return true;
} else {
event.preventDefault();
errors.push("The email must be formated as follows: name#domain.com.");
return false;
}
if (address === null || address === " "){
event.preventDefault();
errors.push("The Address is required.");
return false;
} else {
return true;
}
if(errors.length > 0){
for(var i=0;i<errors.length;i++){
alert(errors)
}
return false;
} else {
return true;
}
}
html:
Send Us An Email
<form enctype="multipart/form-data" action="assets/mailer.php" method="POST" id="form1" onSubmit="return validateForm()">
<label for="Name">Name:</label><br />
<input size="100%" type="text" name="name" id="name"><br>
<label for="Email">E-mail:</label><br />
<input size="100%" type="text" name="email" id="email" value=""><br />
<label for="Phone">Phone Number:</label><br />
<input size="100%" type="text" name="phonenumber" id="phonenumber" value=""><br />
<label for="Address">Shipping Address:</label><br />
<input size="100%" type="text" name="address" id="address" value=""><br />
<label for="comment">Input Comments/Questions:</label><br />
<input size="100%" type="text" name="comment" value=""><br><br>
Please choose a file: <br />
<input name="uploaded" type="file" /><br />
<br />
<input size="100%" type="submit" value="Submit" /><br />
<input size="100%" type="reset" value="Reset">
</form>
<script type="text/javascript" src="./assets/validation.js">
I don't know where to start from, but if you need your own validation you should remove required attribute from the inputs because FF for example will check the form instead of your validation function.
Executing event.preventDefault(); what do you think you have in event?
Properlly you should pass it when calling the function on submit and supply an argument in the function definition
onSubmit="validateForm(event);"
and function definition should be:
function validateForm(event) {
...
so you can do event.preventDefault()
...
}
You may have other problems too, but at least you will get the validation function executed and you;ll have event in it
COMPLETE EXAMPLE ADDED:
<script>
function validateForm(event) {
var phone = document.getElementById("phonenumber").value,
email = document.getElementById("email").value,
name = document.getElementById("name").value,
address = document.getElementById("address").value,
tomatch = /^\d{3}-\d{3}-\d{4}$/,
emailMatch = /^\[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[A-Z]{2,4}$/,
errors = [];
if (!phone){
errors.push("The Phone Number is required.");
} else if (!tomatch.test(phone)){
errors.push("The phone number must be formated as follows: XXX-XXX-XXXX.");
}
if (!name){
errors.push("The Name is required");
}
if (!email){
errors.push("The email is required.");
} else if (!emailMatch.test(email)){
errors.push("The email must be formated as follows: name#domain.com.");
}
if (!address){
errors.push("The Address is required.");
}
if (errors.length) {
event.preventDefault();
alert(errors.join("\n"));
}
}
</script>
<form enctype="multipart/form-data" action="assets/mailer.php" method="POST" id="form1" onSubmit="validateForm(event)">
<label for="Name">Name:</label><br />
<input size="100%" type="text" name="name" id="name"><br>
<label for="Email">E-mail:</label><br />
<input size="100%" type="text" name="email" id="email" value=""><br />
<label for="Phone">Phone Number:</label><br />
<input size="100%" type="text" name="phonenumber" id="phonenumber" value=""><br />
<label for="Address">Shipping Address:</label><br />
<input size="100%" type="text" name="address" id="address" value=""><br />
<label for="comment">Input Comments/Questions:</label><br />
<input size="100%" type="text" name="comment" value=""><br><br>
Please choose a file: <br />
<input name="uploaded" type="file" /><br />
<br />
<input size="100%" type="submit" value="Submit" /><br />
<input size="100%" type="reset" value="Reset">
</form>
Im learning Javascript and am trying to set up a basic form validation which should have the following functionality:
If error is found change text field background color to red, change field value to error message
If no errors are found, proceed
My problem
The validation is working BUT even if no errors is found it still displays an error message...what am I doing wrong?
Code follows:
function validate(){
//form validation
var name=document.getElementById("name");
var surname=document.getElementById('surname');
//name
if (name.value=='') {
name.style.backgroundColor="red";
name.style.color="white";
name.value="Name is required"
return false;
}
else if(isNaN(name)==true){
name.style.backgroundColor="red";
name.style.color="white";
name.value="Name: Only enter letters A-Z"
return false;
}
//surname
if (surname.value == ""){
surname.style.backgroundColor="red";
surname.style.color="white";
surname.value="Surname is required"
return false;
}
else if(isNaN(name)==true){
surname.style.backgroundColor="red";
surname.style.color="white";
surname.value="Surname: Only enter letters A-Z"
return false;
}
return true;
}
HTML
<form id="enquire" method="post">
<h2>Test Drive an Audi Today</h2>
<input type="text" id="name" value="Name" class="textbox" name="name" onfocus="if(this.value=='Name' || this.value=='Name is required' || this.value=='Name: Only enter letters A-Z' ) this.value='';" /><br />
<br />
<input type="text" id="surname" value="Surname" class="textbox" name="surname" onfocus="if(this.value=='Surname') this.value='';" /><br />
<input type="submit" name="submit" class="butt" value="Send" onclick="return validate()" />
You need to pass the value of the input fields to isNaN() like, now you are passing the dom element which will always return true since it is not a number
isNaN(name.value)
Demo: Fiddle
You should use onsubmit event of form instead of click.
<form id="enquire" method="post" onsubmit="return validate()">
I am trying to make a sign-up form that will do client-side validation (check the correct layout of email and matching passwords) before sending any data to the server. I have been having trouble checking to see if the email is in the correct form. I can't get the if(email.indexOf(#))to work correctly. I think I misused the .indexOf()
This is my JavaScript:
function sign_check() {
var email = document.getElementById("sign_email").value;
var user = document.getElementById("sign_user").value;
var pass = document.getElementById("sign_pass").value;
var passcon = document.getElementById("sign_confirm").value;
if(pass !== passcon){
document.getElementById("sign_alert").innerHTML="The passwords do not match"
}
//This part determines whether or not to send the data to the server
if(email.length >= 7){
if(email.indexOf("#")){
if(user.length >= 1){
if(pass.length >= 1){
if(passcon.length >= 1){
if(pass === passcon){
alert("All of the requirements have been met")
}
}
}
}
}
}
}
And this is my html:
<h1 id="pop_up" class="pop_up">Sign Up</h1>
<form id="sign_up" class="sign_up">
<label id="alert_s1" class="alert"> <br /> </label>
<input id="sign_email" class="sign" type="text" placeholder="Email" name="sign_email" /><br />
<label id="alert_s2" class="alert"> <br /> </label>
<input id="sign_user" class="sign" type="text" placeholder="Username" name="sign_user" /><br />
<label id="alert_s3" class="alert"> <br /> </label>
<input id="sign_pass" class="sign" type="text" placeholder="Password" name="sign_pass" /><br />
<label id="alert_s4" class="alert"> <br /> </label>
<input id="sign_confirm" class="sign" type="text" placeholder="Confirm Password" name="sign_confirm" />
</form>
<p id="sign_alert" class="alert"></p>
<button onclick="sign_check()">Submit</button>
Already have an acount? Click here to log in.
</div>
First, your method to validate the email is not very accurate :) Besides that, you're using indexOf incorrectly. Use this instead.
if(email.indexOf("#") != -1 )
You used double quotes "" instead of '' in the ('#'). That should make it work. And === actually works too. The quotation marks were all you needed to change. I hope this helps!
I have a subscription form on my website that I am trying to validate. When the user clicks the button signup the function validate() is called and the fields should get validated however im not getting it to work.
Obviously there are some errors in my code. I have tried to fix it with the little knowledge I have, but can't get it to work. I would greatly appreciate it if you could point me into the right directions as to what I am doing wrong.
Code follows:
function validate()
{
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var nat = document.getElementById("nat").value;
var address = document.getElementById("address").value;
var town = document.getElementById("town").value;
var zip = document.getElementById("zip").value;
var userName = document.getElementById("userName").value;
var password = document.getElementById("password").value;
var password2= document.getElentById("password2").value;
if (name == "" )
{
window.alert("Please Enter your Full Name")
}
checkNr= isNaN(phone)
if(checkNr == true)
{
window.alert("You can only enter numbers. Please try again")
}
if (nat == "")
{
window.alert("Please enter your nationality")
}
if (address == "")
{
window.alert("Please Enter your address")
}
if (password != password2)
{
window.alert("Your passwords did not match. Please re-enter")
}
}
</script>
HTML:
<form name="subscribe">
FULLNAME: </strong><input type="text" id="name"/><br />
PHONE NR: <input type="text" id="phone" onblur="validateForm()" /><br />
NATIONALITY:<input type="text" id="nat" /><br />
Address:<input type="text" id="address" /><br />
Town:<input type="text" id="town" /><br />
Zip Code: <input type="text" id="zip" /><br />
Username: <input type="text" id="userName" /><br />
Password:<input type="password" name="password" /><br />
Retype:<input type="password" name="password2" /><br />
<input type="button" value="submit" onclick="validate()" />
</form>
I found these mistakes in your code:
there is no validateForm() function specified in your phone input field
if you want your form to send data, set the type submit, not button on your submit button
if you want to stop the form submitting when something is not filled, hook the onsubmit event of the form:
<form onsubmit="return validate()"> ... // note the return keyword
and the script
function validate() {
...
if(somethingIsWrong) return false; // false stops submitting
else return true; // do submit
}
also note the getElentById typo mentioned by #FranciscoAfonzo
I found my mistake. It looks like you can not use the document.get with a password input field. I took out the password and it worked. It would be great if I could get some input from someone more experience as to why.
A couple of suggestions:
In JavaScript comparisions are done using === (equal to) and !== (not equal to).
If you have only the variable name in the if loop that will also suffice.
Like:
if (address)
{
window.alert("Please enter your address")
}