0

So, I need a function to check if the rules I've made apply to the options I have in my form.

The first box is a name box and it needs to have at least three letters and contain at least one whitespace to pass. The other box is age, it needs to have a number between 1 and 125, I can do that on my own but I'm thinking there might be a nice way to set all of the rules at once so I thought I'd include it.

The third option is a set of three radio buttons of which one has to be selected and the fourth box is an info box that should consist of a text with at least 30 letters. These rules should be checked on the press of a button, this is how far I've gotten on my own:

var sendButton = $("button:first").addClass("sendButton");
var age = document.getElementsByName('age')[0].value;

sendButton.click(function(){
    var infoName = document.getElementsByName('infoName')[0].value;
    if (infoName.length<3){
    console.log("Your name must consist of at least three letters and contain a whitespace");
    };
    }
});


        <section class="column">
        <h2>Contact us</h2>
        <form action="#">
            <fieldset>
                <legend>Form</legend>
                <div class="textinput">
                    <label for="infoName">Ditt namn:</label>
                    <input type="text" name="infoName" placeholder="ex. John Doe">
                </div>

                <div class="textinput">
                    <label for="infoName">Din ålder:</label>
                    <input type="text" name="age" placeholder="ex. 25">
                </div>

                <div class="radioSelection">
                    <label>Choose your favorite</label>            
                    <input type="radio" name="favorite" id="html" value="html">
                    <label for="html">HTML</label>
                    <input type="radio" name="favorite" id="js" value="js">
                    <label for="js">JavaScript</label>
                    <input type="radio" name="favorite" id="css" value="css">
                    <label for="css">CSS</label>
                </div>

                <div class="textareainput">
                    <label for="info">Info about you:</label>
                    <textarea placeholder="Type something about yourself, this area must contain 30 letters or more"></textarea>
                </div>

                <div class="action">
                    <button>Send</button>
                </div>
Stephan Muller
  • 27,018
  • 16
  • 85
  • 126
Daphen
  • 123
  • 6
  • So is your question how do I check for the number 1 to 125 in the second box? – James Hay Aug 25 '14 at 00:05
  • What? No, the question is how to check all the rules, how to check the number in the second box, I can do myself, as it's exactly the same as I've done to check the length of infoName. – Daphen Aug 25 '14 at 00:11
  • The first part is how do I check to see if there's a whitespace in "infoName", then see if age is between 1-125, then see if a radiobutton is selected, then check if the infobox contains at least 30 letters, all in a nice way. Or do I have to write every if-statement separately? – Daphen Aug 25 '14 at 00:14
  • OK, I guess I'm just struggling to see what you mean by a nice way. It's very easy to write 5 or 6 if statements to validate your form. Without plugging in a whole validation library to provide a slightly shorter syntax, I think that you should just write an if statement for each validation check. – James Hay Aug 25 '14 at 00:17
  • If you do want a validation library which will make it "nicer", check out [Parsley](http://parsleyjs.org/) – James Hay Aug 25 '14 at 00:19
  • I do not want to use any plugins, I guess I just need help with the if-statements then. :) – Daphen Aug 25 '14 at 00:20

1 Answers1

1
function validateForm(){
    var infoName = document.getElementsByName('infoName')[0].value;
    var age= document.getElementsByName('age')[0].value;
    var favourites = document.getElementsByName('favorite');

    var problems = 0;

    if(infoName.length < 3){
        // Failed length validation
        problems++;
    }

    var spaceIndex = infoName.indexOf(' ');

    if(spaceIndex === -1){
        // Name does not contain a space.
        problems++;
    }
    else if(spaceIndex === 0){
        // Name begins with space
        problems++;
    }
    else if(spaceIndex === infoName.length - 1){
        // Space is last character.
        problems++;
    }         

    var hasCheck = false;
    for(var i = 0; i < favourites.length; i++){
        if(favourites[i].checked){
            hasCheck = true;
            break;
        }
    }

    if(!hasCheck){
        // No radio button has been checked.
        problems++;
    }

    var ageNum = parseInt(age);
    if(isNaN(ageNum)) {
        // Age is not a number
        problems++;
    }
    else if(ageNum < 1 || ageNum > 125){
        // Age is not within boundaries
        problems++;
    }

    /// etc etc, for all your validations.

    return problems === 0;
}

At the end of the validation, if any problems are detected, the form will not be submitted (because problems === 0 is false). Also the number validation I've put in there is not very robust. Check out this question which goes into detail about number validation.

The validation method should be called on submission of the form, rather than when the button is clicked

$('form').submit(function(e){
    var valid = validateForm();
    if(!valid){
        e.preventDefault();
        return false;
    }
});
Community
  • 1
  • 1
James Hay
  • 7,115
  • 6
  • 33
  • 57
  • Thanks, looks clean, this was what I meant with "A nice way", I wouldn't have come up with the problemcounter on my own. By the way, you missed one detail, I want to make sure that there's a "space" or "whitespace" in the infoName, is that possible? Also, how do I see if the user has selected one of the radio buttons? – Daphen Aug 25 '14 at 00:32
  • Thanks man, your help is VERY appreciated, you just saved my night. :) Can't upvote you though, I have less than 15 rep. – Daphen Aug 25 '14 at 00:38
  • No worries, I added the check for favourites as well. I haven't actually run all this code I'm just typing it so hopefully you don't get any syntax errors. – James Hay Aug 25 '14 at 00:40
  • If I do, I bet they wont be too overwhelming at least. :) – Daphen Aug 25 '14 at 00:44
  • So, I have a problem, my page is reloading when I press the button most of the time, so I can't see if my validation is working or not. – Daphen Aug 25 '14 at 01:09
  • If you have a submit button in your form then you want the validation to occur on form submission rather than button clicks. This way you can prevent the default behaviour of the form submission (page refresh) rather than the default behaviour of a button click which is nothing. – James Hay Aug 25 '14 at 01:13
  • I'm afraid I have no idea what you're talking about. just .submit instead of .click? Edit: No. My button is a regular – Daphen Aug 25 '14 at 01:16
  • I think by default your button will submit the form unless you set it's type to `button`. Your handler needs to be on the `submit` event of the FORM element. Shouldn't have anything to do with your code being in doc ready – James Hay Aug 25 '14 at 01:22
  • So the easiest solution is the change buttontype to button? Because the default is submit? It isn't in a "form" by the way, it's a regular div with textfields and radiobuttons. On the first click (with nothing printed in the fields), it just reloads, then if I just click it again without typing stuff in, it works and it gives me my errors. So weird. – Daphen Aug 25 '14 at 01:32
  • `
    ` Begs to differ with you. That's in your HTML and the div containing the button is part of that.
    – James Hay Aug 25 '14 at 01:33
  • Should I add the form submit code you wrote inside of the buttonclick? – Daphen Aug 25 '14 at 01:37
  • I just added it instead of the click, now the page doesn't reload if I press it with empty fields, if I however do fill the fields in, it reloads when I press it. – Daphen Aug 25 '14 at 01:39
  • It seems to be the age checker that is the problem. – Daphen Aug 25 '14 at 01:43
  • Check this [fiddle](http://jsfiddle.net/31pwfo0c/2/). Seems to be working correctly? – James Hay Aug 25 '14 at 02:08
  • It is, I don't really know what I added that was wrong but it's working now. However, I can't seem to figure out how to get the length of the text in the infobox. I did this: $('textarea').addClass('infoBox'); var infoBox = $('.infoBox').value.length; if (infoBox<30) { problems++; console.log("You provided too less information"); }; Also, the page will refresh upon successful validation correct? Edit: Line breaks is apparently not available in this comment section. So hard to read code, sorry about that. – Daphen Aug 25 '14 at 02:36
  • You're trying to use the `HTMLElement` `value` property on a jQuery object, not an HTML Element. You can use `value()` on a jQuery object instead. The page technically doesn't 'refresh'. What it does is posts to the URL in the `action` attribute of the form. If the server language doesn't do any redirection, it will return the same page again, which appears to 'refresh' the page. – James Hay Aug 25 '14 at 02:39
  • Why can't I do the same thing that I did with infoName.length? Aren't they the same? infoName = ('.infoName').value and then the length of the value worked in that case, what's different? Oh, I see, but if I want to console.log a success message, the user wont be able to see it before it disappears. – Daphen Aug 25 '14 at 02:45
  • This is really becoming outside the scope of the original question, but what you did originally was retrieve the first HTML element with the name 'infoName'. Pure JS. The second time you did `$('.infoBox')` that doesn't return the element. It is a jQuery function which returns a jQuery object. The methods on this object can then be used to interact with the element it is wrapping. To retrieve the element from the jQuery object you can do this. `$('.infoName')[0]`. – James Hay Aug 25 '14 at 02:48
  • Oh my, it's finally working, everything is working. You're the man. Thanks for all the help, I learned a lot. Have a great day! – Daphen Aug 25 '14 at 02:53
  • Glad you got it sorted :) – James Hay Aug 25 '14 at 03:00