There is something wrong in this line:
var reg = /^[a-z.]+'#'+javaScriptVar$/;
but I don't know how to correctly write this. The current code would make "Please enter Email Address" appear every time. Here are the codes:
<?
$em=$_POST['myemail'];
$ar=split("#",$em);
?>
function validateForm()
{
var x=document.forms["myForm"]["username"].value;
if (x==null || x=="")
{
alert("User Name must be filled out");
return false;
}
if (document.forms["myForm"]["email"].value.length == 0) {
alert("Please enter Email Address");
return false;
} else {
var javaScriptVar = "<?php echo $ar[1]; ?>";
var reg = /^[a-z.]+'#'+javaScriptVar$/;
if (!reg.test(document.forms["myForm"]["email"].value)) {
alert("Please Enter Correct Email Domain");
return false;
}
}
}
You seem to be trying to include an # in your regex to check for url validation. Since there are no quotes used around your regex, specifying it like +'#'+ will not work.
Change it to:
/^[a-z.]#javaScriptVar$/
EDIT:
I think you are using the wrong regex to validate the url. Try this:
/^[a-zA-Z0-9]+[#][a-zA-Z0-9]+.{1}[a-z]{3}$/
Related
So my script perfectly checks whether username is free or not but regardless of that when user submits all forms he is able to register. I need a way to prevent user from registering if username is taken. Here is the code:
index.php
$("#username").keyup(function(){
var val=$("#username").val();
$("#address").html("Your address will be askfolio.com/" + val);
$("#freeu").html("<img src='css/ajax-loader.gif' style='margin-left:-75px;'>");
if (val != ''){
$.ajax({
url:"s/ufree.php",
method:"POST",
data:$("#username"),
success:function(data){
if (data == 1){
$("#freeu").html("<img src='css/accept.png' style='float:left;padding-right:65px;'>");
$("#reg-error").css("display","none");
}else{
$("#freeu").html('');
$("#reg-error").css("display","block");
$("#reg-error").html('Username is already taken, try another.');
$("#username").focus();
return false;
}
}
});
}else {
$("#freeu").html('');
}
});
function Users_Registration()
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $("#name").val();
var lastname=$("#lastname").val();
var username = $("#username").val();
var remail = $("#remail").val();
var rpass = $("#rpass").val();
var day=$("#day").val();
var month=$("#month").val();
var year=$("#year").val();
if(name == "")
{
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter your name in the required field.');
$("#name").focus();
}
else if(lastname == "")
{
$("#reg-error").css("display","block");
$("#reg-error").html(' Please enter your Last Name in the required field.');
$("#lastname").focus();
}
else if(username == ""){
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter your desired username to proceed.');
$("#username").focus();
}
else if(remail == "")
{
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter your email address to proceed.');
$("#remail").focus();
}
else if(reg.test(remail) == false)
{
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter a valid email address to proceed.');
$("#remail").focus();
}else if (rpass == "") {
$("#reg-error").css("display","block");
$("#reg-error").html('Please enter a valid password to proceed.');
$("#rpass").focus();
}
else if (day == ""){
$("#reg-error").css("display","block");
$("#reg-error").html('Please select a day to proceed.');
$("#day").focus();
}else if (month == "") {
$("#reg-error").css("display","block");
$("#reg-error").html('Please select a month to proceed.');
$("#month").focus();
}else if (year == "") {
$("#reg-error").css("display","block");
$("#reg-error").html('Please select a year to proceed.');
$("#year").focus();
}
else
{
var dataString = 'name='+ name + '&lastname='+ lastname + '&username='+ username + '&rpass='+ rpass + '&remail='+ remail + '&year=' + year + '&month=' + month + '&day=' + day +'&page=signup';
$.ajax({
type: "POST",
url: "register.php",
data: dataString,
cache: false,
beforeSend: function()
{
$("#reg-error").html('<br clear="all"><div style="padding-left:115px;"><font style="font-family:Verdana, Geneva, sans-serif; font-size:12px; color:black;">Please wait</font> <img src="images/loadings.gif" alt="Loading...." align="absmiddle" title="Loading...."/></div><br clear="all">');
},
success: function(response)
{
$("#reg-error").html("Loading");
var username="<?php echo $loguser; ?>";
window.location=username;
}
});
}
}
ufree.php
<?php
include "db.php";
if (isset($_POST['username'])) {
$username=$_POST['username'];
$sql=mysql_query("SELECT * FROM users WHERE username='$username'");
if (mysql_num_rows($sql) == 0) {
echo "1";
}else {
echo "<div style='padding-top:4px;'>username is taken</div>";
}
}
?>
Apart from the SQL Injection vulnerability that you have in your sql queries, your approach to username check is somewhat redundant. By checking the username upon every character input you add extra load to the browser and to your server.
I suggest you combine the two processes in one step meaning you do the username check and register in the same place. In your Register.php file check the username availability right before the registration and if the username is taken display a proper message and if not do the registration.
Goes without saying but regardless of the javascript validation, your server still needs to be checking that the username is available at point of registering, since anyone can disable or manipulate the javascript.
Also as Hamed states, your php code is highly vulnerable. At the very least, you should use the following prior to using it in your sql:
$username = mysql_real_escape_string( $_POST[ 'username' ] );
That said, for usability, what you need to do is add an onsubmit function to your form, which checks if the username is valid or not prior to submitting. (summarised your code for simplicity)
var validUser = false;
$("#username").keyup(function(){
var val=$("#username").val();
validUser = false;
if (val != ''){
$.ajax({
url:"s/ufree.php",
method:"POST",
data:val,
success:function(data){
if (data == 1){
validUser = true;
}else{
$("#username").focus();
return false;
}
}
});
}else {
$("#freeu").html('');
}
function formsubmit()
{
if( !validUser )
{
alert( 'Username is already taken, try another' );
return false;
}
return true;
}
Then in your form:
<form action="whatever" onsubmit="return formsubmit();">
...
</form>
Once of my favorite jQuery plugin is the validation eng.
https://github.com/posabsolute/jQuery-Validation-Engine
It has very nice validation for doing just what you are looking for. It does all kinds of fields including inline ajax for username check. If the response from ajax call is not true, then the form won't submit. I use it for my signup forms. Once the user goes to the next field it validates, if it doesn't pass i.e. the username is not available, it will say username not available in red. The form won't submit.
It's not hard to setup. Here is a demo of the ajax. Note it won't actually validate on this demo site but it's an example. You can see how it won't submit though if it's blank or not validated. It's very customizable.
http://www.position-relative.net/creation/formValidator/demos/demoAjaxSubmitPHP.html
Oh course take care of any mysql security issues and check to make sure dupes can't be entered into the database as well.
I am trying to validate my company email-id's in sign up form...so that the form accepts only my company mail id...so now whats the problem here is after validating(ie; when we click submit button then we get an alert message) the form is getting refreshed and the entered values are cleared...so any help or suggestions so that it is not refreshed??thanks in advance...
My Javascript method is:
function submitAlbum() {
var frm = document.getElementById("frmRegistration");
//validateEmail(document.getElementById('email').value);
var email = document.getElementById('email').value;
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
// alert('Submission was successful.');
var r = confirm("Are You Sure You Want to add your details.");
if (r == true) {
frm.action = "signUpServlet?formidentity=doRegistration&checkboxStatus=" + checkboxStatus;
frm.submit();
}
}
else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
return false;
}
}
else {
document.getElementById('email').focus();
alert('Not a valid e-mail address.');
return false;
}
}
I think this will do the job.
<input type = "email" pattern ="^[a-z0-9._%+-]+#bdisys.com">
Check this bin
http://jsbin.com/dew/5/edit
You should bind your validation method to the submit event of your form.
Inside the validation method, stop the event to propagate if the field is invalid, or let it bubble if it's ok.
var frm = document.getElementById("frmRegistration");
frm.addEventListener('submit', validate, false);
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function validate(event) {
// validateEmail
var email = document.getElementById('email').value;
var confirmed = false;
if (re.test(email)) {
confirmed = true;
if (email.indexOf('#bdisys.com', email.length - '#bdisys.com'.length) !== -1) {
confirmed = confirm("Are You Sure You Want to add your details.");
}
} else {
document.getElementById('email').focus();
alert('Email must be a Company e-mail address (your.name#bdisys.com).');
}
if (!confirmed) {
event.preventDefault();
event.stopPropagation();
return false;
}
}
I suggest you to use jQuery to make your code simplier and before all portable.
I have two javascript files that I am using to validate an email address.
validate.js:
function checkEmail(userEmail) {
var email = userEmail
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (emailFilter.test(email.value)) {
//alert('Please provide a valid email address');
//email.focus;
return true;
}
else{
return false
}
}
navigation.js EDIT:
$(document).ready(function() {
//ADDED IMPORTS
var imported = document.createElement('script');
imported.src = 'lib/validation.js';
document.head.appendChild(imported);
console.log("DOCUMENT IS READY!");
var viewsWrapper = $("#views-wrapper");
var loginButton = $("#login-button");
var registerButton = $("#register-button");
// Login Link
// TODO: Unclear if needed
$("ul li.login").click(function() {
$.get('/login', function(data) {
viewsWrapper.html(data);
});
});
$('#usernamefield').blur(function() {
var sEmail = $('#usernamefield').val();
if ($.trim(sEmail).length == 0) {
alert('Please enter valid email address');
e.preventDefault();
}
if (checkEmail(sEmail)) {
alert('Email is valid');
}
else {
alert('Invalid Email Address');
e.preventDefault();
}
});
...(more code follows but not relevant)
I am also using this jade template:
login.jade:
form(action="")
key EMAIL
input(type="text", name="username", id="usernamefield")
p hello world
br
key PASSWORD
input(type="text", name="password", id="passwordfield")
p hello world
br
input(type="submit", name="loginButton", id="login-button", value="LOGIN")
My issue is that when I input something into my email field, I do not get an alert message in any case. Am I allowed to just have to separate javascript files and call the methods I defined in validate.js within navigation.js? I tried putting the validate.js code in navigation.js, but even then it did not work. I would like to keep the files separate. Am I missing something obvious? I want it so that once the user inputs the email, and leaves the field, a message should appear warning if the email is valid or not.
Your help is appreciated.
Is it the blur Event or the checkEmail the problem? try to put a alert() or console.log() just after your blur (and make sure to lose focus on your input). Seperate file shouldn't be a problem. And also have you check for errors in your console ?
JavaScript string has no "value" field
After
var sEmail = $('#username').val();
sEmail becomes a string.
You are passing this string to checkEmail method and try to get "value" from a string:
if(!emailFilter.test(email.value)) {//...}
Replace to
if (!emailFilter.test(email)) {//...}
You are already sending the value of email into checkemail function. So in checkEmail function in validate.js remove email.value in second line of function checkEmail
function checkEmail(userEmail) {
var email = userEmail
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
//alert('Please provide a valid email address');
email.focus;
return false;
}
}
I am trying to use jQuery to see if a user has entered a valid email address into my text box.
Basically, I want the submit button to remain disabled by default, but on each keyup I want to see if the email address is valid, then I want to enable the button. If the user enters a valid email but then deletes parts so that it becomes invalid again (i.e. the # symbol) I want the submit button to become disabled again.
I have a partially working script here. My check or the # symbol works well, but I am having a hard time checking for .com, .co, .net, .org, .edu etc... For some reason, the button keeps enabling even though I have not entered a valid "ending" to the email.
For example "emailco#" is recognized as a valid email. Here is my script:
<script>
$(document).ready(function() {
$('#email').bind('keyup', function(e) {
var email = document.getElementById("email");
if (email.value.search("#") != -1) {
if (
(email.value.search(".com") != -1)||
(email.value.search(".co") != -1)||
(email.value.search(".org") != -1)||
(email.value.search(".net") != -1)||
(email.value.search(".gov") != -1)||
(email.value.search(".biz") != -1)||
(email.value.search(".me") != -1)||
(email.value.search(".edu") != -1)) {
document.getElementById("email_go").disabled = false;
}
else {
document.getElementById("email_go").disabled = true;
}
}
else {
document.getElementById("email_go").disabled = true;
}
});
});
</script>
Just use regex:
if (email.value.search("#") != -1) {
if (/(.+)#(.+)\.(com|edu|org|etc)$/.test(email.value))
}
var email = $('#email').val();
var pattern = ".+\\##.+\\..+";
var valid = email.match(pattern);
if (valid == null) {
alert("Not Valid");
return;
}
else{
alert("Valid");
return;
}
Try this. Of course, this is just a basic example and I'm sure that email addresses nowadays can end in more than just what's specified in the array below. But, still... you get the idea...
// Split the email to see if there's an "#" character
var split = email.split('#');
var split_count = split.length;
// If there is, then split the second string by a "."
if (split_count == 2) {
var domain = split[1].split('.');
var domain_count = domain.length;
if (domain_count == 2) {
// Store all of the accepted values for email endings
var endings = ['org', 'com', 'net', 'edu', 'info', 'biz', 'me'];
var result = $.inArray(domain[1], endings);
// If the final 3 chars of the string are in the array, then proceed
if (result > 0) {
}
}
}
I use this Regex Code to test email format using jQuery:
var email = $('.email').val();
if(email.match(/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/))
{
alert('OK');
}
I have this email form validation script:
<script type="text/javascript" language="javascript">
function validateForm(thisform){
if(thisform.Name.value=="") {
alert("Ooouuupppsss... You did not enter your Name.");
thisform.Name.focus();
return false;
}
if(thisform.Email.value=="") {
alert("Ooouuupppsss... You did not enter a valid Email Address.");
thisform.Email.focus();
return false;
}
if(thisform.Subject.value=="") {
alert("Ooouuupppsss... You did not enter your Subject.");
thisform.Subject.focus();
return false;
}
if(thisform.Message.value=="") {
alert("Ooouuupppsss... You did not enter your Message.");
thisform.Message.focus();
return false;
}
}</script>
Can someone please tell me what do I have to add in this script in order to make the users enter a valid email address. Also I would like in the rest of the fields to make users to enter text (not links).
I've tried to add different pieces of code which I found on different websites but they did not work and this is because I am not sure if I am adding them right.
Thank you for reading my request.
All the best,
Andi
For e-mail checking you can use following code in else part after checking if e-mail is empty
function validateForm(){
var email = document.getElementById("email").value;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
alert("e-mail is not valid");
return false;
}
}
and for url with same logic you can use following regular expression
var urlRegEx = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/;
following is a working example based on your work, you can improve this code it is only for showing you how it should be.
function validateForm(thisform){
if(thisform.Name.value=="") {
alert("Ooouuupppsss... You did not enter your Name.");
thisform.Name.focus();
return false;
}
else{
var name = thisform.Name.value;
if (!checkURL(name)) {
alert("name cannot be a url");
return false;
}
}
if(thisform.Email.value=="") {
alert("Ooouuupppsss... You did not enter a valid Email Address.");
thisform.Email.focus();
return false;
}
else{
var email = thisform.Email.value;
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email.search(emailRegEx) == -1) {
alert("e-mail is not valid");
return false;
}
}
if(thisform.Subject.value=="") {
alert("Ooouuupppsss... You did not enter your Subject.");
thisform.Subject.focus();
return false;
}
else{
if (!checkURL(thisform.Subject.value)) {
alert("subject cannot contain a url");
return false;
}
}
if(thisform.Message.value=="") {
alert("Ooouuupppsss... You did not enter your Message.");
thisform.Message.focus();
return false;
}
else{
if (!checkURL(thisform.Message.value)) {
alert("message cannot contain a url");
return false;
}
}
}
function checkURL(url){
var urlRegEx = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+#)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+#)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%#.\w_]*)#?(?:[\w]*))?)/;
if (url.search(urlRegEx) == -1) {
return true;
}
return false;
}
See this post for regex urls: regular expression for url
See this post for email validation: Validate email address in JavaScript?
See this for X browser event listening, if would use jQuery, ie8 uses attach see this: Javascript add events cross-browser function implementation: use attachEvent/addEventListener vs inline events
I would recommend looping through the form inputs, and checking if its email and if its not run the regex against the link.
(function(){
var validateForm = function(form){
var errors = [], inputs = form.getElementsByTagName('input');
for(var input = 0; input<inputs.length; input++){
var currentInput = inputs[input];
if(currentInput.value === ''){
// handle attributes here for error message, push error message
if(currentInput.attribute('name') === 'email'){
// handle email
// push error message
}
}
}
return errors;
}
var contactForm = document.getElementById('contact');
contactForm.addEventListener('submit', function(e){
var errorMessages = validateForm(contactForm);
if(errorMessages.length === 0){
} else {
e.preventDefault() // stop the form from submitting
// handle your messages
}
}
}());