HTML Form Validation via Javascript - javascript

I want to keep viewers from entering words like "fssadf", and force them to enter a valid email which must contain the "#" in the middle and "." to prevent spam and injection.
I also want the form to display an error message that says "change the email field to the correct email"
I use js_function.js which contain this:
function validEmail()
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var email_address = $("#email").val();
if(reg.test(email_address) == false)
return false;
else
return true;
}
but it does not prevent the viewer from sending me "sfdasfd" instead of a valid email.
What can I do to achieve the above?
check out the files below:
http://www.mediafire.com/?kx5bvttc0s2fbrs
thanks,
rami

Though I didn't see any error on my program what you provided but still you may
use
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
instead of this
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
I think that will help. I provided the total Javascript code what worked properly for me.
function validEmail()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email_address = $("#email").val();
if(reg.test(email_address) == false)
return false;
else
return true;
}
Use this
or you may use this too in other way
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate(this.value)" />
//Other Codes
</form>
And Javascript
<script>
function validate(email)
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
if(reg.test(email) == false)
{
alert("This is a invalid Email Address!");
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
return true;
}
}
</script>
OR
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate()" />
//Other Codes
</form>
And Javascript
<script>
function validate()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email = document.getElementById('email').value;
if(reg.test(email) == false)
{
alert("This is a invalid Email Address!");
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
return true;
}
}
</script>
And the last solution will be quiet easier to apply I think.
Error Message on Page instead of Popup
HTML
<form>
//Other Codes
<input type="text" name="email" id="email" onchange="validate()" />
<span id="errormessage"></span>
//Other Codes
</form>
And Javascript
<script>
function validate()
{
var reg = /^[_a-z0-9]+(\.[a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var email = document.getElementById('email').value;
if(reg.test(email) == false)
{
document.getElementById('errormessage').innerHTML= 'fill your email';
document.getElementById('email').value = '';
document.getElementById('email').focus();
return false;
}
else{
document.getElementById('errormessage').innerHTML= '';
return true;
}
}
</script>

try with this
$(document).ready(function() {
$('#btn-submit').click(function() {
$(".error").hide();
var hasError = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#UserEmail").val();
if(emailaddressVal == '') {
$("#UserEmail").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
else if(!emailReg.test(emailaddressVal)) {
$("#UserEmail").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
}
if(hasError == true) { return false; }
});
});

Duplicate of this question:
Validate email address in JavaScript?
There is some valuable discussion in the comments about edge cases that SHOULD NOT be ignored.
Did you try to Google this one before you asked? IT is a /very/ common question.

If you're after a pure HTML5 solution using jQuery.... Here's a live demo
HTML
<form id="form">
Email <input name="field1" required="required" type="email" /> <br />
<div id="error"></div>
<input required="required" name="submit" type="submit" />
</form>​
Code
$(document).ready(function() {
var validCheckInput = function() {
if ($(this)[0].checkValidity()) {
$(this).removeClass("error");
$("#error").empty();
} else {
$(this).addClass("error");
$("#error").text("change the email field to the correct email");
}
if ($("#form")[0].checkValidity()) {
$("#form input[type='submit']").removeAttr("disabled");
} else {
$("#form input[type='submit']").attr("disabled", "disabled");
}
};s
var binds = function(validCheck) {
$(this).change(validCheck);
$(this).focus(validCheck);
$(this).keyup(validCheck);
validCheck.call($(this));
}
$("#form input").each(function() {binds.call(this, validCheckInput)});
});​
CSS
.error {
border: 2px solid red;
}​

Related

Javascript form validation highlight invalid character

I'm just working on some really basic form validation with JS. I don't want users to be able to use any special characters on input fields as a layer of defense against XSS exploits.
I've got the basic validation down and it seems to work ok but it just says there is an error and I would like to highlight the invalid character. here is my code.
HTML
<head><meta charset="UTF-8"><script src="script.js"></script></head>
<body>
<form method="post" action="test.php" onsubmit="return validate()">
<p><input type="text" id="userName" placeholder="Username or Email"></p>
<p><input type="password" id="userEmail" placeholder="Password"></p>
<p><input type="submit" id="submit" value="Login"></p>
</form>
<input type="button" value="debug" onclick="debug()">
<p id="errorText"></p>
<p id="debug"></p>
</body>
Javascript
<script>
function validate() {
var userName = document.getElementById('userName').value;
var userEmail = document.getElementById('userEmail').value;
var invalidChars = "!,#,#,$,%,^,&,*,(,),<,>,/,~,`";
var mergeFields = userName.concat(userEmail);
var found = "false";
var invCharsArr = invalidChars.split(",");
var fieldsArr = mergeFields.split("");
var nameErr = "false";
var emailErr = "false";
for (var i = 0; i < fieldsArr.length; i++) {
if (invCharsArr.indexOf(fieldsArr[i]) > -1) {
found = "true";
break;
}
}
if (found == "true") {
document.getElementById('errorText').innerHTML = "You used an invalid character";
return false;
}
else {
if (userName == "" || userName == null) {
document.getElementById('userName').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
nameErr = "true";
return false;
}
else if (userEmail == "" || userEmail == null) {
document.getElementById('userEmail').style.backgroundColor = "red";
document.getElementById('errorText').innerHTML = "Field Errors are Highlighted in Red";
emailErr = "true";
return false;
}
else {
return true;
}
}
}
</script>
On a side note I am still a beginner with javascript, if there is anything here that I can do better please let me know I would like to learn. Thanks
You can show an error message under the input marking some chars by wrapping them in spans. Doing this on a input field is not possible as far as I know.
<div class="error">Invalid chars in: <span class="mark">#</span>test</div>.
As already mentioned you should not rely on javascript validation only. It mainly helps to prevent sending unnecessary false requests to the server.

Form validation doesn't like me

Second edit: OH MY GODS I'M AN IDIOT!!! I was focusing on the javascript and completely neglected the lack of a "result" item in the html...Thanks to those who helped!
Edit: Thanks so far. I corrected the errors that people pointed out but it still doesn't like me. :( My html is below.
I'm following a tutorial on html.net (lesson 16 on Javascript) and I've written it exactly how it's supposed to be written. I even loaded up the javascript file of the working tutorial page and compared (was the same)...then copied it and pasted it into my file just to be sure and it still doesn't work. If anyone could offer an opinion, that'd be wonderful. Code is below:
<html>
<head>
<title>Lesson 16: form validation</title>
<script type="text/javascript" src="lesson16.js"></script>
</head>
<body>
<h1>Lesson 16: Form validation</h1>
<form id="myForm" action="#" method="post">
<fieldset>
<p><label for="txtName">Name: </label>
<input type="text" id="txtName" name="txtName" />
</p>
<p><label for="txtEmail">Email: </label>
<input type="text" id="txtEmail" name="txtEmail" />
</p>
<p><input type="submit" value="Submit" /></p>
</fieldset>
</form>
</body>
</html>
function init()
{
var myForm = document.getElementById("myForm");
myForm.onsubmit = validate;
}
onload = init;
function validate()
{
var name = document.getElementById("txtName").value;
var email = document.getElementById("txtEmail").value;
var isRequiredNameSet = false;
var isRequiredEmailSet = false;
var isEmailValid = false;
var message = "";
isRequiredNameSet = validateRequired(name);
isRequiredEmailSet = validateRequired(email);
isEmailValid = validateEmail(email);
if (isRequiredNameSet && isRequiredEmailSet && isEmailValid)
{
message = "Thank you, you know how to follow instructions...good for you.";
}
else if (! isRequiredNameSet)
{
message = "Please, enter a name. First thing and you got it wrong...";
writeMessage(message);
return false;
}
else if (! isRequiredEmailSet)
{
message = "Please, enter an email...come on, it's not that hard...";
writeMessage(message);
return false;
}
else if (! isEmailValid)
{
message = "A valid email, numb nuts...with an # symbol and a .com or whatever...GODS!!";
writeMessage(message);
return false;
}
alert(message);
}
function validateRequired(input)
{
var isValid = false;
if (input.length == 0)
{
isValid = false;
}
else
{
isValid = true;
}
return isValid;
}
function validateEmail(email)
{
var isValid = false;
if (email.indexOf("#") == -1 || email.indexOf(".") == -1)
{
isValid = false;
}
else
{
isValid = true;
}
return isValid;
}
function writeMessage(text)
{
var paragraph = document.getElementById("result");
if (paragraph.firstChild)
{
paragraph.removeChild(paragraph.firstChild);
}
paragraph.appendChild(document.createTextNode(text));
}
you have IsRequiredNameSet in the else if (in validate function), but it should be isRequiredNameSet.
NOTE: you can chage your validateRequired() ... to function validateRequired(input) { return !!input.length; }
The problem is the line myForm.onsubmit = validate();... where you are invoking the validate function instead os assigning it as a reference to onsubmit
myForm.onsubmit = validate;
The same applies to onload also
onload = init;
Then you have a problem in case of isRequiredEmailSet
function validate() {
var name = document.getElementById("txtName").value;
var email = document.getElementById("txtEmail").value;
var isRequiredNameSet = false;
var isRequiredEmailSet = false;
var isEmailValid = false;
var message = "";
isRequiredNameSet = validateRequired(name);
isRequiredEmailSet = validateRequired(email);
isEmailValid = validateEmail(email);
if (isRequiredNameSet && isRequiredEmailSet && isEmailValid) {
message = "Thank you, you know how to follow instructions...good for you.";
} else if (!isRequiredNameSet) {
message = "Please, enter a name. First thing and you got it wrong...";
writeMessage(message);
return false;
} else if (!isRequiredEmailSet) {
message = "Please, enter an email...come on, it's not that hard...";
writeMessage(message);
return false;
} else if (!isEmailValid) {
message = "A valid email, numb nuts...with an # symbol and a .com or whatever...GODS!!";
writeMessage(message);
return false;
}
alert(message);
}
Demo: Fiddle

Facebook Registration Plugin with RegExp

I need to validate a field in my the Facebook Registration plugin. I need to ensure that no special characters or spaces are used on the handle field. The preg_match works great with php but not sure how do do with with Javascript.
This is what I have for my if statement. Even when I used the proper text for the handle field it still comes up invalid.
var thisRegex = new RegExp('^(_|([a-z]_)|[a-z])([a-z0-9]+_?)*$/i');
if(!thisRegex.test(form.handle)){
errors.handle = "No spaces or special characters.";
}
Here is the full form code:
{"name":"name"},
{"name":"handle", "description":"Username - Letters & Underscores Only", "type":"text"},
{"name":"email"},
{"name":"country", "description":"Country", "type":"select", "options":{"United States":"United States","Canada":"Canada","Other":"Other"}},
{"name":"password"},
]'
redirect-uri="http://www.mystoragelink.com"
width="320"
onvalidate="validate">
</fb:registration>
<script>
function validate(form) {
errors = {};
var thisRegex = new RegExp('^(_|([a-z]_)|[a-z])([a-z0-9]+_?)*$/i');
if(!thisRegex.test(form.handle)){
errors.handle = "No spaces or special characters.";
}
return errors;
}
</script>
<head>
<script>
function ValidateForm()
{
var fname =document.getElementById('fname').value;
var lname=document.getElementById('lname').value;
var email= document.getElementById('email').value;
var pwd=document.getElementById('pwd').value;
//var email= document.getElementById('email');
if(email!='')
{
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(document.getElementById('email').value)) {
return true;
}
else
{
alert('Please provide a valid email address');
document.getElementById('email').focus();
return false;
}}
if(fname == '')
{
alert("plz enter your firstname");
return false;
}
else if(lname == '')
{
alert("plz enter your lastname");
return false;
}
else if(email == '')
{
alert("plz enter your email address");
return false;
}
// var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
// else if (!filter.test(document.getElementById('email').value;))
// {
// alert('Please provide a valid email address');
// email.focus;
// return false;
//}
else if(pwd == '')
{
alert("plz enter your password");
return false;
}
}
</script>
</head>
<form action="login.php" method="POST">
<table border="1">
<tr>
<tr><td>First Name:</td><td><input type="text" name="fname" id="fname"></td></tr><br>
<tr><td>Last Name:</td><td><input type="text" name="lname" id="lname"></td></tr><br>
<tr><td> Email:</td><td><input type="text" name="email" id="email"></td></tr><br>
<tr> <td>Password:</td><td><input type="password" name="pwd" id="pwd">`enter code here`</td></tr><br>
<tr><td><input type="submit" value="Insert"onclick="return ValidateForm();"></td></tr>
</tr>
</form>
**I think this will help You**
Thanks for your efforts. I was able to find my problem.
in the var the last /i of the RegExp('^(|([a-z])|[a-z])([a-z0-9]+_?)*$/i') needed to be removed.
Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
Here is the working code:
var thisRegex = new RegExp("^(_|([a-z]_)|[a-z])([a-z0-9]+_?)*$");
if(!thisRegex.test(form.handle)){
errors.handle = "No spaces or special characters.";
}

form validation error

I have little problem with form and I am using js for validation.
Here is my form code.
<form method="get" onkeydown="checkEnter()" action="emailform.php" id="signupform" name="subscribe">
<input name="email" id="email" type="text" value="Enter Email for Updates" onfocus="if(this.value=='Enter Email for Updates'){this.value=''};" />
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
id signupform I am using for validation and submit the form is on pressing enter button.
But there is problem when put signupform then my validation start working fine and when I enter correct email it's show me error and when I remove the signupform id then my form submission work fine without validation.
Here is my JS code for id signupform.
function SubscribeForm() {
$('#signupform').submit(function () {
$('.email').removeClass('error')
$('em.error').remove();
var error = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($.trim($('.email').val()) == '') {
$(this).append('<em class="error">Please enter your email address.</em>');
$(this).addClass('error');
error = true;
} else if (!emailReg.test(jQuery.trim($('.email').val()))) {
$(this).append('<em class="error">Please enter a valid email address</em>');
$(this).addClass('error');
error = true;
}
if (!error) {
$("#submit", this).after('<span id="form_loading"></span>');
var formValues = $(this).serialize();
$.post($(this).attr('action'), formValues, function (data) {
$("#signupform").before(data);
});
$(':input[type="text"]').attr('value', '');
}
return false
});
}
change
return false
to
return error;
it is causing problem.
change
return false;
to
return !error;
Also, add css class "email" to input email field, or change jquery to selector code ".email" to "#email"
Also a possible solution, if you don't need to support the old browser: placeholder.
<input placeholder="Enter email" type="text"... />
Thanks for your help Guys. i just put this and now working fine.
$('#signupform').submit(function(){
$('.email').removeClass('error')
$('em.error').remove();
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
sEmail = document.getElementById('email').value;
if (filter.test(sEmail)) {
return true;
}
else {
if(sEmail == '')
{
$(this).append('<em class="error">Please enter your email address</em>');
$(this).addClass('error');
}
else
{
$(this).append('<em class="error">Please enter a valid email address</em>');
$(this).addClass('error');
}
return false;
}
});
});

Single else clause for multiple if clauses - javascript

First: I'm JavaScript newbie.
So.. I have basic form with password, repeat password, email and repeat email fields. I want to check if password is equal to repeat password. If it's not, alert message appears and page reloads. Same for email and repeat email.
BUT if pass and repeat password aren't equal AND email and repeat email aren't equal, first alert message appears, then the second message (this time for email) appears too fast. I want to show only one alert message when both fields don't match.
<script type="text/javascript">
function checkFields() {
var pass= document.getElementById('password');
var reppass= document.getElementById('reppass');
var email= document.getElementById('email');
var repemail= document.getElementById('repemail');
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
}
else if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
}
</script>
And the form:
<form onSubmit="checkFields()">
<p><label>Password:</label> <input name="password" id="password" required="true" type="password" /></p>
<p><label>Repeat password:</label> <input name="reppass" id="reppass" required="true" type="password" /></p>
<p><label>Email:</label> <input name="email" id="email" required="true" type="email" /></p>
<p><label>Repeat Email:</label> <input name="repemail" id="repemail" required="true" type="email" /></p>
<p><input type="submit" value="Send"></p>
</form>
You can simply return from the if clauses like this:
function checkFields() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
if (pass.value != reppass.value && email.value != repemail.value) {
alert('Both fields dont match');
window.location.reload();
}
if (pass.value != reppass.value) {
alert('Passwords dont match');
window.location.reload();
return;
}
if (email.value != repemail.value) {
alert('Emails dont match');
window.location.reload();
return;
}
}
I like this style, because it prevents nesting if clauses. The downside is, that you have multiple return points that can be confusing - this heavily depends on the length of the function.
EDIT
Updated order of if blocks
if( condition1 ) {
}else if( condition2 ) {
}else{
…
}
I believe this is what you want.
One solution would be to break the validation up into separate methods, then only run the second validation if the first one succeeds.
Here's an example:
var FormValiditor = function() {
var pass = document.getElementById('password');
var reppass = document.getElementById('reppass');
var email = document.getElementById('email');
var repemail = document.getElementById('repemail');
return {
checkFields: function() {
if(checkPassword()){
return checkEmail();
}
return false;
},
checkPassword: function() {
if (pass.value != reppass.value) {
alert("Password don't match");
return false;
}
return true;
},
checkEmail: function() {
if(email.value != repemail.value){
alert("Emails do not match");
return false
}
return true
}
}
}();
Then, if you're using jQuery(which you should be!) you can run validation when the form gets submitted.
$('form').submit(FormValidator.checkFields);
if ...
else if ...
else if ...
...
else ...
That's how it should be structured. You can have as many else ifs as you like.

Categories

Resources