0

I need some help with this javascript code. I want to validate Nights tax box and name text box, so they have a value in them. The Night text box must only accept a numeric number.

Here is my code

$(document).ready(function() {
    
    var emailPattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
    //var numeric =  /^[0-9]+$/;
    var regex = /[0-9]|\./;
        
        $(":text, #error").after("<span>*</span>");
        $("arrival_date").focus();
        
    $(document).on("click", "#submit", function (e) {
        
        var valid = true;
        
        if ($("#name").val() === "") {
            $("#name").next().text("This field is required.").css({
                "color": "#FF0000",
                "font-size": "13px"
            });
            valid = false;
        }
        else {
            
            valid = true;
        }
        
        if ($("#nights").val() === "") {
            valid = false;
            $("#nights").next().text("This field is required.").css( {
                "color": "#FF0000",
                "font-size": "13px"
            });
        } else if (!regex.test("nights")) {
            $("#nights").next().text("This field is required.").css( {
                "color": "#FF0000",
                "font-size": "13px"
            });
            valid = false;
        }
        else {
            valid = true;
        }
ad
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Reservation request</title>
	<link rel="stylesheet" href="main.css">
	<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<script src="http://code.jquery.com/jquery-latest.min.js"></script>
	<script src="reservation.js"></script>
</head>
	
<body>
	<h1>Reservation Request</h1>
	<form action="response.html" method="get"
    	name="reservation_form" id="reservation_form">
		<fieldset>
        	<legend>General Information</legend>
        	<label for="arrival_date">Arrival date:</label>
        	<input type="text" name="arrival_date" id="arrival_date" autofocus><br>
        	<label for="nights">Nights:</label>
        	<input type="text" name="nights" id="nights"><br>
        	<label>Adults:</label>
        	<select name="adults" id="adults">
        		<option value="1">1</option>
        		<option value="2">2</option>
        		<option value="3">3</option>
        		<option value="4">4</option>        		        		        		
        	</select><br>
        	<label>Children:</label>
        	<select name="children" id="children">
        		<option value="0">0</option>
        		<option value="1">1</option>
        		<option value="2">2</option>
        		<option value="3">3</option>
        		<option value="4">4</option>        		        		        		
        	</select><br>        	
		</fieldset>
		<fieldset>
        	<legend>Preferences</legend>
        	<label>Room type:</label>
			<input type="radio" name="room" id="standard" class="left" checked>Standard&nbsp;&nbsp;&nbsp;	        	
			<input type="radio" name="room" id="business" class="left">Business&nbsp;&nbsp;&nbsp;
			<input type="radio" name="room" id="suite" class="left last">Suite<br>
        	<label>Bed type:</label>
			<input type="radio" name="bed" id="king" class="left" checked>King&nbsp;&nbsp;&nbsp;
			<input type="radio" name="bed" id="double" class="left last">Double Double<br>
			<input type="checkbox" name="smoking" id="smoking">Smoking<br>
		</fieldset>		
		<fieldset>
    		<legend>Contact Information</legend>
    		<label for="name">Name:</label>
			<input type="text" name="name" id="name"><br>
        	<label for="email">Email:</label>
        	<input type="text" name="email" id="email"><br>
			<label for="phone">Phone:</label>
			<input type="text" name="phone" id="phone" placeholder="999-999-9999"><br>
		</fieldset>

		<input type="submit" id="submit" value="Submit Request"><br>

	</form>
</body>
</html>

UPDATED Code.

$(document).ready(function() {

var emailPattern = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
//var numeric =  /^[0-9]+$/;
var regex = /[0-9]|\./;

    $(":text, #error").after("<span>*</span>");
    $("arrival_date").focus();


function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
} 
$(document).on("click", "#submit", function (e) {

    var valid = true;

    if ($("#name").val() === "") {
        $("#name").next().text("This field is required.").css({
            "color": "#FF0000",
            "font-size": "13px"
        });
        valid = false;
    }

    if ($("#nights").val() === "") {
        valid = false;
        $("#nights").next().text("This field is required.").css( {
            "color": "#FF0000",
            "font-size": "13px"
        });
    } else if (isNumeric("#nights")) {
        $("#nights").next().text("This field is required.").css( {
            "color": "#FF0000",
            "font-size": "13px"
        });
        valid = false;
    }

     if (valid === false)
         e.preventDefault();

});        });

I was hopping that someone could help me

2
  • If your question is all about js, please, remove all the unnecessary code, such as css, it make the question harder to read Commented Dec 5, 2016 at 3:32
  • I just remove the css. Can you please help me Commented Dec 5, 2016 at 3:38

1 Answer 1

1

You can use existing functions to check if an input is numeric (taken from here):

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

and you can use HTML5's input type number:

<input type="number" min="1" max="5">

Your current regex won't work since it will return true for any string that contains any kind of numbers, which is not the intended behavior.

Your usage of the variable valid is also incorrect: as your code is now, your form input will return as valid if #nights is properly validated - it will ignore the result of your name's input.

Sign up to request clarification or add additional context in comments.

5 Comments

So how can I fix it so it wouldn't ignore the name's input
@Jabateh Remove the else lines where you set valid = true;. valid is true at the start, so without else branches it will be false if any of your validations have failed (and not be overwritten to true).
Sorry I am new to javascript. I did what you told me, but when I but a string value (ex: a or b or th) in the Nights text box, and put some value in the name text box, and click submit. It accept it. But what I really want is to accept numeric number a words. I just update the code, Where it said UPDATED Code. Can you please, please look at it and tell me what I am doing wrong.
@Jabateh You wrote else if (isNumeric("#nights")), which means it will fail when input IS numeric. You want the opposite: else if (!isNumeric("#nights")). Don't forget to accept an answer if it has helped you.
That is true. I Finally caught that after when I took a break from my code for 10 minutes. And also I was calling my text box value before I could click the submit but. Anyway thank so much for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.