Email check with jQuery doesn't work - javascript

I tried to make Ajax form and tried to make email verification there. I found this solution
http://jsfiddle.net/EFfCa/
but can't turn it on in my script:
<script>
$('#joinForm').ajaxForm(function() {
var testEmail = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $("input[name=name]")
var email = $("input[name=email]")
if(name.val()==''||email.val()=='') {
$(".notify").show();
$(".notify p").text('empty');
} else if(testEmail.test(email.value)) {
$(".notify").show();
$(".notify p").text('email is wrong');
} else {
$(".notify").show();
$(".notify p").text('good');
}
});
</script>
The form always passed verification even email is wrong. Verification for empty fields works good...

The following line else if(testEmail.test(email.value)) will return true if the email is correct.
In your logic that's where the email is wrong could that be the problem?

This is because your passing email.value. jquery objects don't have a parameter called value, so this will resolve as undefined.
.test() returns true if it is passed undefined, so your test will always pass.
use .val() instead.

$('input').blur(function() {
var testEmail =/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (testEmail.test(this.value)) alert('passed');
else alert('failed');
});

Related

How to pass boolean result in "If condition"

I have a function in my ionic app to check if user email is already exists in firebase database.
checkValidEmail(email):any{
let result=this.userService.getUserByEmail(email);
console.log(result);
result.subscribe((k:User[])=>{
if(k.length>0){
return true;
}else{
return false;
}
});
}
I am trying to pass its boolen result in following if condition to check whether entered email address is already exists in database. It it exists display an error.
if(this.checkValidEmail(this.user.email)){
console.log("Error : Already has this email address ");
this.error ="Already has this email address in out system";
}
But I cant get true or false into if(this.checkValidEmail(this.user.email)) . Please help I'm new in this.
The result object is an asynchronous stream and the subscribe callback triggers at a later time so checkValidEmail doesn't return a result.
You can use a callback and get that callback to trigger or you could use promises or RxJS observables.
To keep things simple I have changed your code with a simple callback function.
checkValidEmail(email,resultCallback){
let result=this.userService.getUserByEmail(email);
console.log(result);
result.subscribe((k:User[])=>{
if(k.length>0){
resultCallback(true);
}else{
resultCallback(false);
}
});
}
Revise the code as follows
this.checkValidEmail(this.user.email,(isError)=>{
if (isError){
console.log("Error : Already has this email address ");
this.error ="Already has this email address in out system";
}
});

How to style Validation checking before "save"

This is just a best practice question that I have run into and can't find the answer for. Any input is welcome! (Backed up responses with data/research would be amazing)
Example Save Button
When my save button is pressed, I want to do some validation, name (must be first and last), age (must be from 0 - 125), email (valid email address) and if these are all true, I want to "save" the user (to a db or wherever doesn't matter)
Right now my functions are set up
// Global error handler for example
var errors = {};
// Save Button Function
saveButton = function(dataModel) {
var valid = true;
valid = validateName(valid, dataModel.name);
valid = validateAge(valid, dataModel.age, 'extraParam');
valid = validateEmail(valid, dataModel.email, 'secondParam', 'thirdParam');
valid = (dataModel.red) ? validateRedUser(valid, dataModel) : valid;
if (valid) {
// Save user to database
}
else {
// alert to user an error has occured
// user errors object to respond with the errors
}
}
I feel like passing around the valid state to each sub validation function is not the best approach to a problem like this. It works, but can it be improved?
Edit: A sub-validation function would look something like:
validateName = function(valid, dataModel.name) {
if (!dataModel.name) {
valid = false;
// access global error handler to save error
errors.name = 'error in the name';
}
return valid;
}
Taking your sample function added the valid state condition check.
validateName = function(valid, dataModel.name) {
if (!dataModel.name && valid) {
valid = false;
// access global error handler to save error
errors.name = 'error in the name';
}
return valid;
}

CRM: Javascript to Check Email Validation and Prevent Saving if not Valid

On CRM 2013 on-premise, I'm working to write a javascript that checks for email validation. The field can contain a list of email address, however if the email is not valid, it will not let the users save the form.
I got the splitting and validating to work fine now.
However I continue to have problems to prevent users from saving the form.
On the OnChange, I check the box on the "Pass execution context as first parameter"
I user the preventDefault() function as suggested by an MSDN article however I keep getting error message "Unable to get property 'preventDefault' of undefined or null reference".
Any idea is appreciated. Here's my code:
function EmailTest(EmailField)
{
var Email = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if(Email.test(EmailField))
{
return true;
}
else
{
return false;
}
}
function CheckEmailString(context)
{
try
{
var EmailString = context.getEventSource().getValue();
if (EmailString != null)
{
var separator = [" ", ",", ";", "|"];
var EmailArray = EmailString.split(separator);
var Flag = true;
for(var i = 0;i < EmailArray.length;i++)
{
if(!EmailTest(EmailArray[i]))
{
Flag = false;
break;
}
}
if(Flag != true)
{
alert("The list of emails entered contain invalid email format. Please re-enter");
context.getEventArgs().preventDefault();
}
}
}
catch(err)
{
alert(err.message);
}
}
you get the error
Unable to get property 'preventDefault' of undefined or null reference
because the getEventArgs is available only when you are inside the save event, it's not available inside onchange event.
You should add the validation check also inside the save event if you want to stop the save.
Could I suggest you might try updating it to the full version of the method ie
Xrm.Page.context.getEventArgs.preventDefault().
I understand when working in CRM you have to reference use the full names in order for your function to see the prevent default method.
Hopefully that helps but if not good luck in seeking a solution

Azure - Server Validation

Okay, so I am attempting to validate on the server side. I am using Windows Azure Mobile Services for my Android application. The validation is done in Javascript / Node.js.
I have been doing my best to find solutions to my issue and stumbled upon [this link] (http://blogs.msdn.com/b/carlosfigueira/archive/2012/09/21/playing-with-the-query-object-in-read-operations-on-azure-mobile-services.aspx)!
I intend to use regexp to validate the object before persisting it to the DB.
I would understand how to do this 'pre-query' but as I need access to use regex, I must perform 'post-query' filtering.
Below is the code in which I have (so far) but I want to know how can I validate many fields and deliver appropriate error messages for each invalid fields. If all are valid, then persist to the DB.
Thanks in advance!
function insert(item, user, request) {
var userTable = tables.getTable('User');
userTable.where({email: item.email}).read({
success: emailExists
});
function emailExists(existingItems)
{
if (existingItems.length > 0)
{
request.respond(statusCodes.CONFLICT,
"An account is already registered with this email!.");
}
else
{
// Insert the item as normal.
request.execute({
success: function (results)
{
var regexEmail = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var filtered = results.filter(function(item)
{
return regexEmail.test(item.email);
});
request.respond(statusCodes.OK, filtered);
}
});
}
}
}
If I understand what you want to do correctly, you first need to validate the input's e-mail against the items in the database (to maintain unicity), then validate other fields in the input before inserting that. If that's the case, then after the query validation (to prevent duplicate e-mails) you can validate the item fields individually, as shown in this document. The code below shows an example of such validation.
function insert(item, user, request) {
var userTable = tables.getTable('User');
userTable.where({email: item.email}).read({
success: emailExists
});
function emailExists(existingItems)
{
if (existingItems.length > 0)
{
request.respond(statusCodes.CONFLICT,
"An account is already registered with this email!.");
}
else
{
// Validate fields *before* inserting
var regexEmail = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!regexEmail.test(item.email)) {
request.respond(statusCodes.BAD_REQUEST, { error: 'E-mail is invalid' });
return;
}
if (!item.name || item.name.length < 10) {
request.respond(statusCodes.BAD_REQUEST, { error: 'Item must have a name of at least 10 characters' });
return;
}
// If all validation succeeded, then insert the item
request.execute();
}
}
}

Jquery domain validation after adding http

I need to do a URL validation for a CS form. I already have a script there that that checks for http and adds it if not there. However, if I add another function to do just validation, no matter where I put it, it returns URL invalid.
This is what I am running
<script type="text/javascript">
$(function(){
$('.url').blur(function(e) {
if ($(this).val().match(/^http/) || $(this).val().match(/^https/)) /*define the http & https strings */ {
$.noop() /*if strings exist, do nothing */
}
else {
// get value from field
var cur_val = $(this).val();
// do with cur_val
$(this).val('http://' + cur_val);
}
});
});
</script>
This is the second function I used for validation:
<script type="text/javascript">
function validate() {
var url = document.getElementById("url").value;
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if (pattern.test(url)) {
alert("Url is valid");
return true;
}
alert("Url is not valid!");
return false;
}
</script>
What am I doing wrong? I've tried to merge the 2 functions but my js skills choose that exact moment to fail.
Thank you!
I don't know, if this is what you are exactly looking for,
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
pattern.test("http://google.com"); // True
pattern.test("google.com"); // False
The if condition you are using is useless, since you return the result of the pattern match anyway.
So the updated Validate function should simply return the pattern results & should look like:
function validate() {
var url = document.getElementById("url").value;
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
return pattern.test(url);
}
Assuming that there is a DOM element with id url.
Just from an immediate look, it looks like your "add http" function is looking for tags with class="url", while the validate function is looking for tags with id="url". If you have nothing with that id, then I suppose it would always return invalid.

Categories