简体   繁体   中英

How can i write function called validate(z) which takes a string as argument & return true if contain 1 “@” symbol & at least 1 “.” & false otherwise

I have just started to learn functions and am finding it quite difficult.

I have learnt a few different functions but I haven't ever done a function like this.

How do I write a function called validate(z) which takes a string as an argument and returns true if it contains one @ symbol and at least one dot . and false otherwise.

Eg if z = "stack@overflow.co.uk" the function will return true .

Regex seems like a lot of overkill for such a simple requirement. I'd go with something like this

function validate(z) {
    var hasDots = z.indexOf('.') !== -1,
        firstAt = z.indexOf('@'),
        lastAt = z.lastIndexOf('@');

    return hasDots && firstAt !== -1 && firstAt === lastAt;
}

It sounds like what you're looking for is an email validation function. These are a lot more tricky to write than you may expect. You have to validate length as well as format. Here's one that's worked well for me in all of my implementations using a (quite complicated) regex statement.

function validateEmail(v) {
    var r = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
    return (v.match(r) == null) ? false : true;
}

You can use regex.

function validate(z) {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    return re.test(z);
}

For the dot, use indexOf to search for the character in the input:

function contains(z, c) { 
  return z.indexOf(c) !== -1; 
}

To check for a single @ , you could say

function contains_one(z, c) {
  var first = z.indexOf(c);
  var last  = z.lastIndexOf(c);
  return first !== -1 && first == last;
}

function validate(z) {
  return contains_one(z, '@') && contains(z, '.');
}

If you prefer to use regexp:

function validate(z) {
  return /^[^@]*@[^@]*\.[^@]*$/.test(z);
}

This says asks for a sequence of non-at-signs, followed by an at-sign, followed by a sequence of non-at-signs, followed by a dot, followed by a sequence of non at signs. You may want to tweak this. For instance, it insists that the dot be to the right of the at sign. Also, it allows the dot to come immediately after the at-sign, or immediately at the end of the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM