Validating email using indexOf() - javascript

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!

Related

disable all other inputs if command/specific input not filled in

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/

check if input value not equal to integer then don't submit form

i have a simple php email form, but i am getting spam emails. I have added a check input, User have to fill the input. If input value equal to 12 then submit the form, otherwise don't submit the form with a popup error.(Please do the math.)
<form action="" method="post">
<input type="text" name="name" placeholder="name" required>
<input type="text" name="email" placeholder="email" required>
<input type="text" name="phone" placeholder="phone" required>
<div class="check">
<label>6 x 2 =</label>
<input type="text" name="not_robot" required="required">
</div>
<input type="submit" value="submit">
</form>
i am using php method below:
if(isset($_POST['not_robot']) !== 12 && isset($_POST['not_robot']) !== ''){
echo '<script type="text/javascript">alert("Please do the math, if you are human.");</script>';
}else{
//email script here
}
when i submit form, error popup appear saying "Please do the math, if you are human", but after i close the popup, it also send email.
Any help appreaciated Thanks
P.S: if check method is possible using javascript or jquery it would be a great help.
You need to test on the client:
Plain JS
window.onload=function() {
document.querySelector("form").onsubmit=function(e) {
var val = this.elements["not_robot"].value;
return !isNaN(val) && parseInt(Number(val)) == val && !isNaN(parseInt(val, 10);
}
}
jQuery:
$(function() {
$("form").on("submit",function(e) {
var val = $("[name='not_robot'"].val();
if (isNaN(val) || !parseInt(Number(val)) == val || isNaN(parseInt(val, 10)) e.preventDefault();
}
}
Try to check when submitting the form. Go with below code or link-
JSFiddle
HTML Code-
<form action="" method="post">
<input type="text" name="name" placeholder="name" required>
<input type="text" name="email" placeholder="email" required>
<input type="text" name="phone" placeholder="phone" required>
<div class="check">
<label>6 x 2 =</label>
<input type="text" name="not_robot" required="required">
</div>
<input type="submit" value="submit">
</form>
JAVASCRIPT Code-
$('form').submit(function() {
if (parseInt($('input[name="not_robot"]').val()) == 12) {
return true;
}
else{
alert('You not enterd the correct value');
return false;
}
});
Don't try to prevent sending spam mail this way. My suggestion is to apply csrf protection and also google captcha. You can use this library for csrf protection. And for google captcha use this
If you want to validate through PHP..Below is the way
if(is_numeric($_POST['not_robot']) && !empty($_POST['not_robot'])){
echo '<script type="text/javascript">alert("Please do the math, if you are human.");</script>';
}else{
//email script here
}
Ways :
Use PHP exit() function to exits the current script execution.we can use this function with (or without) an message.
Syntax : exit(message) OR exit()
We can also use return;
Here, the control will return to the script that invoked the running of that file.
Try this :
if(isset(($_POST['not_robot']) != '12') && (isset($_POST['not_robot']) !== '')){
/* alert here */
exit();
}else{
//email script here
}
HTML:
<form action="" method="post" name="form1">
<input type="text" name="name" placeholder="name" required>
<input type="text" name="email" placeholder="email" required>
<input type="text" name="phone" placeholder="phone" required>
<div class="check">
<label>6 x 2 =</label>
<input type="text" name="not_robot" id="not_robot" required="required" />
</div>
<input type="button" value="submit" onClick="checkForm()">
</form>
JavaScipt:
function checkForm()
{
if(document.getElementById('not_robot').value == "12" && document.getElementById('not_robot').value != "")
{
alert('ok');
document.forms['form1'].submit();
}else{
alert('not ok');
}
}

Check if an input with class is empty in a form

I wrote a code to validate a form on client-side. Since I binded all the error messages on('input', function()) now the last case to take in consideration is when the user didn't even hit a required input leaving it empty.
If all the inputs in the form were required I could have used something like
$('#subButton').on('click', function(e) {
if (!$('#formName').val()) {
e.preventDefault();
alert("Fill all the required fields");
});
But since in my form there are required inputs (with class="req") and non required inputs, I would like to know if there's a method to perform the check only on the .req inputs.
Something like:
$('#subButton').on('click', function(e) {
if (!$('#formName.req').val()) {
e.preventDefault();
alert("Fill all the required fields");
}
});
In other words I would like to perform the identical check which the up-to-date browsers do if the HTML required option is specified, just to be sure that, if the browser is a bit old and doesn't "read" the required option, jQuery prevents the form to be sent.
Just use .filter and check the length. Also, a simple ! check probably isn't good, what if someone enters 0?
var hasEmptyFields = $('#formName.req').filter(function() {
return this.value.replace(/^\s+/g, '').length; //returns true if empty
//Stole the above regex from: http://stackoverflow.com/questions/3937513/javascript-validation-for-empty-input-field
}).length > 0
if (hasEmptyFields) {
}
Use reduce
const submitAllowed = $('.req').toArray().reduce((result, item) => {
return result && (!!item.value || item.value === 0);
}, true)
if (!submitAllowed) { ... }
Here is a simple demo:
<form action="dummy.asp" onSubmit="return handleSubmit()">
<p> You can only submit if you enter a name </p>
<br />
Enter name: <input class="req" type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function handleSubmit() {
const submitAllowed = $('.req').toArray().reduce((result, item) => {
return result && (!!item.value || item.value === 0);
}, true)
return submitAllowed;
}
</script>
But since in my form there are required inputs (with class="req")
and non required inputs, I would like to know if there's a method to
perform the check only on the .req inputs
There is an HTML5 form boolean attribute required.
required works on:
<input type="text" />
<input type="search" />
<input type="url" />
<input type="tel" />
<input type="email" />
<input type="password" />
<input type="date" />
<input type="number" />
<input type="checkbox" />
<input type="radio" />
<input type="file" />
Example:
input {
display: block;
margin: 6px;
}
<form action="http://www.stackoverflow.com/">
<input type="text" placeholder="This is required" required />
<input type="text" placeholder="This isn't required" />
<input type="text" placeholder="This is required" required />
<input type="text" placeholder="This isn't required" />
<input type="submit" value="Press Me Without Filling in any of the Fields">
</form>
Peculiarly, the StackOverflow Snippet above doesn't seem to be working.
Here's a JSFiddle to demonstrate what it should be doing:
https://jsfiddle.net/a5tvaab8/

how to validate input fields on change and enable submit button

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.

validation of form inputs in JavaScript

I want to validate a input fields of form in javascript. I have searched a lot on net and always got different ways to do it. It was so confusing. I want for every single input if it is left empty an alert should popup. Here is my code
<form method="post" action="form.html" id="FormContact" name="frm">
<p>Full Name: <br /><br /> <input type="text" name="FullName" size="50" id="Name"></p>
<span id="error"></span>
<p>Email:<br /><br /> <input type="email" name="Email" size="50" id="Mail"></p>
<p> Subject:<br /><br /> <input type="text" name="subject" size="50" id="Subject"></p>
Message:<br /><br />
<textarea rows="15" cols="75" name="Comment" id="text">
</textarea> <br /><br />
<input type="submit" value="Post Comment">
</form>
I got it done sometimes but that only worked for Full Name field.
Thanks and regards,
You can do something like this, to have an alert popup for each empty input.
$('form').on('submit', function(){
$('input').each(function(){
if($(this).val() === ""){
alert($(this).attr('name') + " is empty");
}
});
});
http://www.w3schools.com/js/js_form_validation.asp
if you're willing to use javascript, this would be pretty easy to implement.
use jquery validation plugin.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script>
$("#FormContact").validate({
rules: {
FullName: {
required:true
}
},
messages:{
FullName:{
required:"Please Enter FullName."
}
}
});
</script>
USE submit method of jquery the use each loop to validate the controls
LIVE CODE
$('form#FormContact').submit(function(){
var i= 0;
$('input').each(function(i,j){
if($(this).val() == "" || $(this).val() == undefined){
alert('empty');
i++;
}else{
i=0;
}
})
if(i == 0){
return false;
}else{
return true;
}
})

Categories