简体   繁体   中英

Check for space form validation

I have a jsfiddle here - http://jsfiddle.net/1Lo7ag21/6/

I have a name input where I would like the first and second name

I'm trying to validate a name field by checking for a space.

How can I check that the field contains a space and display the alert if it doesn't

    $('button').click(function(e){

        e.preventDefault();

        var name = $('#name').val();

        if(name.length == 0 && name.indexOf(' ') === -1){
            alert('Add first and last name with a space');
        }

    })

You can do somethong like this:

var name = $('#name').val();
name =       name.replace(/^\s+|\s+$/g,"") ;  // strip any leading or trailing spaces
name  = name.replace(/\s+/g," ");  // remove multiple intermediate spaces
if (!/(^[A-Za-z]\s[A-Za-z-   ']$)/.test(name)) {   // first and second names separated by a space, allow for hyphen and apostrophe
   alert ("You must enter your first name and last name separated by a space");
}

Looks like you've nearly got it, but your condition is a little off.

if(name.length == 0 && name.indexOf(' ') === -1){

You're checking that the name length is both 0 (empty string) and does not contain a space. You probably meant to use || (or) here.

if(name.length === 0 || name.indexOf(' ') === -1){

http://jsfiddle.net/1Lo7ag21/13/

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