Facebook Registration Plugin with RegExp - javascript

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.";
}

Related

How to make email id in a form optional in JavaScript

I'm creating a form and validating it with JS. I want to make the email id optional. Either i can be left blank or filled. But i want to validate the email id only if the something's typed in the field. And i must use regexe.
"email":{
"regex":"/^([\.a-z0-9_\-]+[#][a-z0-9_\-]+([.][a-z0-9_\-]+)+[a-z]{1,4}$)/i",
"alertText":"* Invalid email address"}
What are the changes should me made here?
You'd have to do a two step validation I think. Apply a different validation check for the email field if its empty.
Since it's Javascript can you do something like:
if (str === '') {
validations['email'] = {}
} else {
validations['email'] = {
// email validation
}
}
I don't know of any other way to do it then that. Maybe there's something you can do with a regex like a condition check but considering how regex work I don't think that it is possible.
Try this
var $email = $('form input[name="email'); //change form to id or containment selector
var re = /[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}/igm;
if ($email.val() != '' && !re.test($email.val()))
{
alert('Please enter a valid email address.');
return false;
}
Try it :
if(email.length > 0) {
//Test Email is Valid Or Not
}
Final code :
<html>
<head>
</head>
<body>
Enter Email : <input type="text" id="txt">
<button onclick="isValid()">Test</button>
<script>
var ele = document.getElementById("txt");
function isValid(){
var email = ele.value;
var patt = /^[a-zA-Z0-9_\-]+#[a-zA-Z0-9_\-]+\.[a-z]{1,4}$/i;
if(email.length > 0) {
if(patt.test(email))
alert("Valid Address Email");
else
alert("Invalid address Email");
}
else
alert("Email is Empty : Valid Address Email");
}
</script>
</body>
</html>
Check links
<input style="margin-top: 20px;" type="text" placeholder="Enter an Email ID" name="Email" id="Email" pattern="((\w+\.)*\w+)#(\w+\.)+(com|kr|net|us|info|biz)" required="required">

how to validate text area with out any phonenumber,name,emailid,urls

how to validate the text area field with out these values phone number, email address or any url in your messages .
if any of the details given automatically reject messages with contact information?? suggest me
<form action="main.php" method="post">
<textarea data-questionable="true" id="message_body" name="message_text" rows="7" class="submit-text-box"></textarea>
<br/>
<input type='submit' name='send' Value='Send Details' onclick='validate()' />
</form>
Your question is kind of unclear but it sounds like you want to make sure there are no phone numbers, email addresses or urls in a text area. Below is some code to validate that each piece is NOT existent in the text area. The following code will alert if any of those three fields are present in the text area.
Phone Number:
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
alert("message");
return false;
}
else
{
return true;
}
}
Email:
var emailPat = /^(\".*\"|[A-Za-z]\w*)#(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/
var EmailmatchArray = Email.match(emailPat);
if (EmailmatchArray != null) {
alert("Text contains an email!");
return false;
}else{
return true;
}
URL:
var Url = "^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$";
var isURL = WebUrl.match(Url);
if (isURL != null) {
alert("Contains a URL.");
return false;
}else{
return true;
}

Validating a form in Javascript not working

I'm trying to validate a form using JavaScript, but the code doesn't seem to execute. The Form is being processed using php which is working just fine. But, the validation is not working. Can someone please help me with this.
<script>
function validateForm(){
var x = document.getElementById('name');
var email = document.getElementById('email');
var num = document.getElementById('number');
var size = document.getElementById('size');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var atpos=email.value.indexOf("#");
var dotpos=email.value.lastIndexOf(".");
if (x.value == null || x.value == "") {
alert("Please Enter your name");
x.foucs;
x.style.background = 'Yellow';
return false;
}
if(!filter.test(email.value){
alert('Please provide a valid email address');
email.focus;
email.value="";
return false;
}
if(num.value == null && num.value == ""){
alert('Please enter your mobile number');
num.focus();
}
if(!isNan(num.value){
alert('Please enter a valid number');
num.focus();
num.style.background();
return false;
}
return false;
}
</script>
And here is my html code.
<form method="post" name="myForm " onsubmit="return validateForm()" action="myprocessingscript.php" >
<input type="text" name="name" placeholder="Name" class="text" id="name" />
<input name="email" placeholder="Email" type="text" class="text" id="email"/>
<input name="number" placeholder="Mobile Number" type="text" class="text" id="number"/>
<input name="size" placeholder="Size" type="text" class="text" id="size" />
<input type="Submit" value="Submit" class="button">
Working fiddle
Correct the spelling of foucs and ensure all references have parenthesis such as:
email.focus();
Without parenthesis, the function is not called. It's valid Javascript but it won't do anything.
You also missed a closing ) here:
if(!filter.test(email.value){
// ^ add another )
and here:
if(!isNan(num.value){
// ^ add another )
!isNan(....) should be isNaN(....). Javascript is case sensitive and you shouldn't be "notting" it here. isNaN is saying "is not a number" so it's already "notted".
On the line below, style has no background function. Looks like you want to assign a value here not call a function:
num.style.background(); // change to assign value.
On this line, change && to ||:
if(num.value == null && num.value == ""){
// ^ should be ||
Finally, remove the return false at the end.
Try using x.focus();
x.foucs; is not a valid statement, and neither is email.focus;.
These aren't right I don't think:
email.focus;
// Try email.focus();
and
x.foucs;
// Try x.focus();
Also looking at your code I don't see a </form>
Try this:
function validateForm(){
var x = document.getElementById('name');
var email = document.getElementById('email');
var num = document.getElementById('number');
var size = document.getElementById('size');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var atpos = email.value.indexOf("#");
var dotpos = email.value.lastIndexOf(".");
if (x.value == null || x.value == "") {
alert("Please Enter your name");
x.focus();
x.style.background = 'Yellow';
return false;
}
if(!filter.test(email.value){
alert('Please provide a valid email address');
email.focus();
email.value="";
return false;
}
if(num.value == null || num.value == ""){
alert('Please enter your mobile number');
num.focus();
return false;
}
if(!isNaN(num.value)){
alert('Please enter a valid number');
num.focus();
num.style.background = "Yellow";
return false;
}
return true;
}

HTML Form Validation via 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;
}​

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